Skip to content

Instantly share code, notes, and snippets.

@growvv
Created November 22, 2020 10:19
Show Gist options
  • Save growvv/d9c37640aa94d8b56be1d27e1ce1d3fd to your computer and use it in GitHub Desktop.
Save growvv/d9c37640aa94d8b56be1d27e1ce1d3fd to your computer and use it in GitHub Desktop.
表格控件简单示例。在主ViewCOntroller中实现UITableViewDataSource和UITableViewDelegate协议
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var ctrlnames: [String]?
var tableView: UITableView?
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
// 初始化数据
self.ctrlnames = ["hello", "world", "good", "morning"]
// 创建表视图
self.tableView = UITableView(frame: self.view.frame, style: .plain)
self.tableView!.delegate = self
self.tableView!.dataSource = self
// 创建一个重用的单元格
self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "SwiftCell")
self.view.addSubview(self.tableView!)
// 创建表头标签
let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 30))
headerLabel.backgroundColor = UIColor.green
headerLabel.numberOfLines = 0
headerLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
headerLabel.text = "常见UIKit控件"
headerLabel.font = UIFont.italicSystemFont(ofSize: 20)
self.tableView!.tableHeaderView = headerLabel
}
/* UITableViewDataSource */
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ctrlnames!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 为了提高表格显示性能,已创建完成的单元需要重复使用
let identify: String = "SwiftCell"
let cell = tableView.dequeueReusableCell(withIdentifier: identify)
cell!.accessoryType = .disclosureIndicator
cell!.textLabel!.text = self.ctrlnames![indexPath.row]
return cell!
}
/*UITableViewDelegate*/
// func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!)
// {
// self.tableView?.deselectRow(at: indexPath as IndexPath, animated: true)
// print("hhhh")
// let itemString = self.ctrlnames![indexPath.row]
// let alertView = UIAlertController(title: "提示", message: "你选中了【\(itemString)】", preferredStyle: UIAlertController.Style.alert)
// alertView.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
// self.present(alertView, animated: true, completion: nil)
//
// }
}
@growvv
Copy link
Author

growvv commented Nov 22, 2020

不知为啥,实现UITableViewDelegate协议的函数没起作用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment