import UIKit
class TableViewController: UIViewController {
var tableView = UITableView()
var dataList: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.title = "使用系统cell";
self.view.backgroundColor = UIColor.white
// 右上角编辑按钮
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .edit, target: self, action: #selector(editAction))
self.dataList = NSMutableArray.init(array: ["🐰", "秃子", "鹰酱", "毛熊", "棒子", "脚盆鸡", "高卢鸡", "狗大户", "🐫", "沙某", "河马"])
createTableViewUI()
}
func createTableViewUI() {
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.backgroundColor = UIColor.red
// self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(clickBackBtn))
tableView = UITableView.init(frame: self.view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(self.tableView)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID");
}
@objc func clickBackBtn() {
self.tableView .reloadData();
}
@objc func editAction() {
tableView.setEditing(true, animated: true)
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .done, target: self, action: #selector(doneAction))
}
@objc func doneAction() {
self.tableView.setEditing(false, animated: true)
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .edit, target: self, action: #selector(editAction))
}
}
extension TableViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataList.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
cell.textLabel?.text = self.dataList[indexPath.row] as? String
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alertC = UIAlertController.init(title: "温馨提示", message: "确定要删除\(dataList[indexPath.row])?", preferredStyle: .alert)
alertC.addAction(UIAlertAction.init(title: "确定", style: .destructive, handler: { (UIAlertAction) in
self.dataList.removeObject(at: indexPath.row)
self.tableView.reloadData()
}))
alertC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
present(alertC, animated: true, completion: nil)
print("要删除\(dataList[indexPath.row])")
}
}
}