swift UITableView

2017-02-21  本文已影响16人  天蚕
//原始写法
import UIKit
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{
    override func loadView() {
        let tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.frame = UIScreen.mainScreen().bounds
        view = tableView
    }
    
    lazy var dataList = {["小史","教授","小飞","陈伟"]}()
    
    //MARK: - UITableView的数据源方法和代理方法
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        
        if cell == nil
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        }
        
        cell?.textLabel?.text = dataList[indexPath.row]
        
        return cell!
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
}
//苹果官方建议将代理和数据源方法单独写道一个扩展中,以便于提高代码可读性
import UIKit

class ViewController: UIViewController {
    override func loadView() {
        let tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.frame = UIScreen.mainScreen().bounds
        view = tableView
    }
    
    lazy var dataList = {["小史","教授","小飞","陈伟"]}()
}

//MARK: - UITableView的数据源方法和代理方法
extension ViewController: UITableViewDelegate,UITableViewDataSource{
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        
        if cell == nil
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        }
        
        cell?.textLabel?.text = dataList[indexPath.row]
        
        return cell!
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
}
上一篇 下一篇

猜你喜欢

热点阅读