UITableView的创建

简介: UITableView的创建
import UIKit
 class ViewController: UIViewController {
 override func viewDidLoad() {
    super.viewDidLoad()
    // tabview的创建,遵守协议是用逗号 "," 来实现的
    let tableview = UITableView()
    // tableview�的frame的设置
    tableview.frame = CGRect(x:0,y:64,width:UIScreen.main.bounds.width,height:UIScreen.main.bounds.height)
    // tableview的背景色
    tableview.backgroundColor = UIColor.brown
    // tableview挂代理
    tableview.delegate = self
    tableview.dataSource = self
    // tableview的分割方式
    tableview.separatorStyle = UITableViewCellSeparatorStyle.none
    // tableview添加到view上面
    view.addSubview(tableview)
}
// MARK:  数据源加载
 lazy var datalist: [String] =  {
    return ["1","2","3","4","5"]
  }()
 }
// MARK: 苹果官方推荐将数据源代理方法单独写到一个拓展方法里面,以便提高代码的可读性
// extension: 相当于OC里面的 category 这样代码更简洁
extension ViewController:UITableViewDelegate,UITableViewDataSource{
// MARK: tableView段里面的 段落 数
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
// MARK: tableView段里面的 行 数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return datalist.count
}
// MARK: tableView cell 的设置
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default,reuseIdentifier:"cellID")
        cell?.selectionStyle = UITableViewCellSelectionStyle.none
    }
    cell?.textLabel?.text = datalist[indexPath.row]
    return cell!
}
// MARK: tableView 的点击事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("\(indexPath.section)段,\(indexPath.row)行")
}
 // MARK: tableView cell 的高度返回值
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return 100
  }
}
目录
相关文章
|
4月前
|
开发者 iOS开发
介绍 UITableView 和 UICollectionView,它们的区别是什么?
介绍 UITableView 和 UICollectionView,它们的区别是什么?
67 0
|
iOS开发 容器
(五)UITableView的用法一
(五)UITableView的用法一
163 0
UITableView使用中的一些刁专问题总结
tableview中cell的系统分隔线问题(分隔线顶满或者缩短)
UITableView使用中的一些刁专问题总结