美文网首页
swift UITableView

swift UITableView

作者: 天蚕 | 来源:发表于2017-02-21 10:48 被阅读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
    }
}

相关文章

网友评论

      本文标题:swift UITableView

      本文链接:https://www.haomeiwen.com/subject/zsegkttx.html