16.UITableView的創(chuàng)建

 import UIKit

 class ViewController: UIViewController {

 override func viewDidLoad() {
    super.viewDidLoad()
   
    // tabview的創(chuàng)建,遵守協(xié)議是用逗號 "," 來實(shí)現(xiàn)的
    let tableview = UITableView()
    // tableview?的frame的設(shè)置
    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:  數(shù)據(jù)源加載
 lazy var datalist: [String] =  {

    return ["1","2","3","4","5"]

  }()
 }

// MARK: 蘋果官方推薦將數(shù)據(jù)源代理方法單獨(dú)寫到一個拓展方法里面,以便提高代碼的可讀性
// extension: 相當(dāng)于OC里面的 category 這樣代碼更簡潔
extension ViewController:UITableViewDelegate,UITableViewDataSource{

// MARK: tableView段里面的 段落 數(shù)
func numberOfSections(in tableView: UITableView) -> Int {
    
    return 1
}

// MARK: tableView段里面的 行 數(shù)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return datalist.count
}

// MARK: tableView cell 的設(shè)置
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 的點(diǎn)擊事件
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
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容