import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ var ctrlnames:[String]? var tableView:UITableView? override func viewDidLoad() { super.viewDidLoad() self.ctrlnames = ["UILabel","UITextField","UIButton","UISwitch","UISegmentControl","UIImageView","UIProgressView","UISlider","UIAlertView"] self.tableView = UITableView(frame:self.view.frame, style: .plain) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cellID") self.view.addSubview(self.tableView!) //建立表頭標籤 let frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 30) let headerLabel = UILabel(frame: frame) headerLabel.backgroundColor = UIColor.black headerLabel.textColor = UIColor.white headerLabel.numberOfLines = 0 headerLabel.lineBreakMode = .byWordWrapping headerLabel.text = "常見的 UIKit 控件" headerLabel.font = UIFont.italicSystemFont(ofSize: 20) self.tableView?.tableHeaderView = headerLabel } //表格行數 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.ctrlnames!.count } //單元顯示內容 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identyfy:String = "cellID" let cell = tableView.dequeueReusableCell(withIdentifier: identyfy, for: indexPath) cell.accessoryType = .disclosureIndicator cell.textLabel?.text = self.ctrlnames![indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView?.deselectRow(at: indexPath, animated: true) let itemString = self.ctrlnames![indexPath.row] let alertController = UIAlertController(title: "提示", message: "你選中了\(itemString)", preferredStyle: .alert) let okAction = UIAlertAction(title: "肯定", style: .default, handler: nil) alertController.addAction(okAction) self.present(alertController, animated:true, completion: nil) } //滑動刪除必須實現的方法 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let index = indexPath.row self.ctrlnames?.remove(at: index) self.tableView?.deleteRows(at: [indexPath], with: .bottom) } //滑動刪除 func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } //修改刪除按鈕的文字 func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "刪除" } }