016--swift编写tableview实战

//
//  ViewController.swift
//  tableView讲解
//


import UIKit


// OC:@interface ViewControlleer() <UITableViewDatasourece>
// Swift中如下
class ViewController: UIViewController,UITableViewDataSource
{

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    func setupUI() {
        // 1、创建表格
        let tableView = UITableView(frame: view.bounds, style: .plain)
        // 2、添加到视图
        view.addSubview(tableView)

        // 3、注册可重用 cell [UITableViewCell class](这里是一个注意点,用classForCoder())
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")

        //设置数据源
        //Swift中没有遵守协议是一个错误
        tableView.dataSource = self

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

        cell.textLabel?.text = "哈哈--\(indexPath.row)"

        return cell
    }

}


猜你喜欢

转载自blog.csdn.net/liyunxiangrxm/article/details/78980748