//
// ViewController.swift// SimpleTable//// Created by Ray Zhang on 2017/10/28.// Copyright © 2017年 Ray Zhang. All rights reserved.//import UIKit
class ViewController: UITableViewController,UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!var cityListDic:NSDictionary! //定义字典类型变量var cityGroupName:NSArray!//定义城市组数组override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let cityListPath = Bundle.main.path(forResource: "citydict", ofType: "plist")//获取文件路径 let city = NSDictionary(contentsOfFile: cityListPath!)//获取文件内容 self.cityListDic = city let tempList = cityListDic.allKeys as NSArray//获取字典所有key值 //tempList.sortedArray(using: Selector("compare:"))//排序 cityGroupName = tempList self.tableView.dataSource = self self.tableView.delegate = self self.searchBar.delegate = self self.searchBar.sizeToFit()}//UITableView数据源协议方法,定义table中节的数目。override func numberOfSections(in tableView: UITableView) -> Int { return self.cityGroupName.count}//UITableView数据源协议方法,定义每个section的标题override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.cityGroupName[section] as? String}//UITableView数据源协议必须实现的方法,定义每个section中的行数。override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let groupName = cityGroupName[section] as! String let citylist = self.cityListDic[groupName] as! NSArray return citylist.count}//UITableView数据源协议必须实现的方法,定义索引override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return self.cityGroupName as? [String]}复制代码
//UITableView数据源协议必须实现的方法,定义每个单元格现实的内容,返回Cell对象
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let cellIdentifer = "cellIdentifer" var cell:UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifer) if (cell == nil){ cell = UITableViewCell(style: UITableViewCellStyle.default , reuseIdentifier: cellIdentifer) } let section = indexPath.section //当前section ID let row = indexPath.row //该section内的row ID let groupName = cityGroupName[section] as! String let citylist = self.cityListDic[groupName] as! NSArray cell.textLabel?.text = citylist[row] as? String cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator return cell}//UITableDelegate协议的方法,选中某一行时触发override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = indexPath.section //当前section ID let row = indexPath.row //该section内的row ID let groupName = cityGroupName[section] as! String let citylist = self.cityListDic[groupName] as! NSArray let value = citylist[row] as? String NSLog(value!)}override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.}复制代码
}