import UIKit
class TableViewControllerMain: UITableViewController {
//MARK: - TsetData
//在这里准备一些测试数据,供table使用
var item1 =ProvinceAndCities(province:"浙江", cities: ["杭州","宁波","温州"])
var item2 =ProvinceAndCities(province:"江苏", cities: ["南京","苏州","扬州"])
var item3 =ProvinceAndCities(province:"山东", cities: ["济南","青岛","威海"])
var provinceCityList:[ProvinceAndCities] = []
overridefunc viewDidLoad() {
super.viewDidLoad()
//载入数据
provinceCityList = [item1,item2,item3]
//在有导航的情况下,back按钮默认在导航条左边,如果把editButtonItem也放在左边,
//则会把back按钮取代了,就无法返回了。所以把edit按钮放右边
//editButtonItem具有批量删除功能
navigationItem.rightBarButtonItem =editButtonItem
}
//MARK: - Table view data source
//Section的个数与省的个数对应
overridefunc numberOfSections(in tableView:UITableView) -> Int {
returnprovinceCityList.count
}
overridefunc tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
returnprovinceCityList[section].cities.count
}
//每个Section的单元数与城市个数对应
overridefunc tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell {
iflet cell = tableView.dequeueReusableCell(withIdentifier:"reuseIdentifier", for: indexPath)as?TableViewCellCustom {
cell.tableCellLabel.text =provinceCityList[indexPath.section].cities[indexPath.row]
return cell
}
return tableView.dequeueReusableCell(withIdentifier:"reuseIdentifier", for: indexPath)as!TableViewCellCustom
}
//将每个section的头部title设为省名
overridefunc tableView(_ tableView:UITableView, titleForHeaderInSection section:Int) -> String? {
returnprovinceCityList[section].province
}
// 这个函数返回true时,启动滑动删除功能
overridefunc tableView(_ tableView:UITableView, canEditRowAt indexPath:IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
returntrue
}
// 实现滑动删除功能
overridefunc tableView(_ tableView:UITableView, commit editingStyle:UITableViewCellEditingStyle,forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// 执行删除任务时,先要删除数组里的数据,然后再执行tableView.deleteRows,否则会崩溃
var updateData =provinceCityList[indexPath.section].cities
updateData.remove(at: indexPath.row)
provinceCityList[indexPath.section].cities = updateData
tableView.deleteRows(at: [indexPath], with: .fade)
ifprovinceCityList[indexPath.section].cities.count == 0 {
// 当检测到省对应的城市删光时,删除该省对应的section,同样也是先删除数组里的数据,然后才执行视图tableView.deleteSections
provinceCityList.remove(at: indexPath.section)
tableView.deleteSections(IndexSet.init(integer: indexPath.section), with: .fade)
}
} elseif editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row tothe table view
}
}
}