TableView

使用代码创建一个UITableView对象

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    // MARK:- 懒加载的属性

    var tableView : UITableView = {
        () -> UITableView in
        let tempTableView = UITableView()
        return tempTableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.frame = self.view.bounds
        self.view.addSubview(self.tableView)
        self.tableView.dataSource = self
    }


    // MARK:- UITableViewDataSource的方法

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellId = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
        if cell == nil
        {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellId)
        }
        cell?.textLabel?.text = String(indexPath.row)

        return cell!
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}

使用扩展来实现TableView的协议和协议方法

import UIKit

class ViewController: UIViewController {

    // MARK:- 懒加载的属性

    var tableView : UITableView = {
        () -> UITableView in
        let tempTableView = UITableView()
        return tempTableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
    }

    func configUI(){
        self.tableView.frame = self.view.bounds
        self.view.addSubview(self.tableView)
        self.tableView.dataSource = self
    }
}

extension ViewController : UITableViewDataSource
{
    // MARK:- UITableViewDataSource的方法

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellId = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
        if cell == nil
        {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellId)
        }
        cell?.textLabel?.text = String(indexPath.row)

        return cell!
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

}

通过xib注册Cell

photoPicker.register(UINib.init(nibName: "ZFPhotoPickerCell", bundle: nil), forCellWithReuseIdentifier: photoCellId)

results matching ""

    No results matching ""