1 import UIKit
2
3 class ViewController:UIViewController,UITableViewDataSource {
4
5 var countries:Dictionary<String, [String]> = [“A”:
[“Afghanistan”, “Albania”, “Algeria”, “Angola”, “Australia”,
“Austria”, “Azerbaijan”], “B”:
[“Bangladesh”,“Belgium”,“Bhutan”,“Bolivia”,“Brazil”,“Bahrain”,
“Bulgaria”],“C”:
[“Canada”,“Congo”,“Chile”,“China”,“Colombia”,“Cuba”],“D”:
[“Denmark”,“Djibouti”,“Dominica”], “E”:
[“Egypt”,“Estonia”,“Ethiopia”], “F”:
[“Fiji”,“Finland”,“France”], “G”:
[“Gambia”,“Germany”,“Greece”], “H”:
[“Haiti”,“Honduras”,“Hungary”], “I”:
[“India”,“Indonesia”,“Iran”,“Ireland”,“Iraq”,“Italy”], “J”:
[“Jordan”, “Japan”], “K”:[“Kazakhstan”,“Korea”,“Kuwait”],
“L”:[“Laos”,“Libya”,“Lebanon”], “M”:
[“Madagascar”,“Morocco”,
“Malaysia”,“Mexico”,“Mali”,“Mozambique”], “N”:
[“Nepal”,“Netherlands”,“Nigeria”,“New Zealand”], “O”:
[“Oman”], “P”:
[“Pakistan”,“Panama”,“Philippines”,“Portugal”], “Q”:
[“Qatar”], “R”:[“Romania”,“South Africa”, “Russia”], “S”:
[“Serbia &
Montenegro”,“Senegal”,“Singapore”,“Somalia”,“Switzerland”],
“T”:[“Thailand”, “Turkmenistan”,“Tunisia”,“Turkey”],
“U”:[“United Arab Emirates”,“United States of America”,
“Uzbekistan”], “V”:[“Vanuatu”,“Venezuela”,“Vietnam”],
“Y”:[“Yemen”], “Z”:[“Zambia”,“Zimbabwe”]]
6
7 var keys:[String] = []
8
9 override func viewDidLoad() {
10 super.viewDidLoad()
11 // Do any additional setup after loading the view,
typically from a nib.
12
13 keys = Array(countries.keys).sorted()
14
15 let screenRect = UIScreen.main.bounds
16 let tableRect = CGRect(x:0, y:20, width:
screenRect.size.width, height:screenRect.size.height - 20)
17 let tableView = UITableView(frame:tableRect)
18
19 tableView.dataSource = self
20
21 self.view.addSubview(tableView)
22 }
23
24 func numberOfSections(in tableView:UITableView) ->
Int {
25 return keys.count
26 }
27
28 func tableView(_ tableView:UITableView,numberOfRowsInSection section:Int) -> Int{
29 let subCountries = countries[keys[section]]
30 return (subCountries?.count)!
31 }
32
33 func tableView(_ tableView:UITableView,
titleForHeaderInSection section:Int) -> String?{
34 return keys[section]
35 }
36
37 func sectionIndexTitles(for tableView:UITableView) -
[String]?{
38 return keys
39 }
40
41 func tableView(_ tableView:UITableView,
cellForRowAt indexPath:IndexPath) -> UITableViewCell {
42
43 let identifier = “reusedCell”
44 var cell =
tableView.dequeueReusableCell(withIdentifier:identifier)
45
46 if(cell == nil){
47 cell = UITableViewCell(style:
UITableViewCellStyle.default, reuseIdentifier:identifier)
48 }
49
50 let subCountries = countries[keys[(indexPath as
NSIndexPath).section]]
51 cell?.textLabel?.text = subCountries![(indexPath as
NSIndexPath).row]
52
53 return cell!
54 }
55 }
//索引表格需要用的代理方法
image.png
image.png