class ViewControllerI:
UIViewController,UITableViewDelegate,UITableViewDataSource {
var mytableView : UITableView?
let testValue:NSString = "这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容\n这是测试内容"
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
mytableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.frame.width, height: view.frame.height) , style: .plain)
mytableView?.tableFooterView = UIView()
mytableView?.delegate = self // 设置代理
mytableView?.dataSource = self
mytableView?.estimatedRowHeight = 60
mytableView?.rowHeight = UITableViewAutomaticDimension
view .addSubview(mytableView!)
//注册UITableView,cellID为重复使用cell的Identifier
mytableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
}
/*
@注意:我们前边的ViewController继承了UITableViewDataSource
@和 UITableViewCelegate。如果我们不注册下面的三个方法XCode就会报错!!!
*/
// 列数
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// 行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
// 创建 UITableViewCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cells = (tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)) as UITableViewCell
cells.textLabel?.text = testValue as String
return cells
}
// 点击响应事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
// 分割线无间距
override func viewDidLayoutSubviews() {
mytableView?.separatorInset = .zero
mytableView?.layoutMargins = .zero
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = .zero
cell.layoutMargins = .zero
}
Swift 4.0 纯代码实现UITableView
最新推荐文章于 2023-03-06 19:27:16 发布