21.Swift中tableView的使用

// 遵守協議的方式,直接在繼承的父類後跟,+協議即可

class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        

        // 添加tableView的控件

        let tableView = UITableView()

        tableView.frame = self.view.bounds

        self.view.addSubview(tableView)

        

        // 設置數據源,設置數據

        tableView.dataSource = self

        tableView.delegate = self

    }


    

}


// 相當於OC中的category

extension ViewController : UITableViewDataSource

{

    // MARK:- 實現數據源方法

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1

    }

    

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 20

    }

    

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let ID : String = "Cell"

        var cell = tableView.dequeueReusableCellWithIdentifier(ID)

        

        if cell == nil {

            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: ID)

        }

        

        cell?.textLabel?.text = "測試數據:\(indexPath.row)"

        

        return cell!

    }

}


extension ViewController : UITableViewDelegate

{

    // MARK:- 實現代理方法

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        print(indexPath.row)

    }

}


// UITableViewDataSource和UITableViewDelegate 可以放在一起

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章