Swift学习记录 -- 15.tableView的创建与基本操作

来源:互联网 发布:vue.js event.target 编辑:程序博客网 时间:2024/05/19 16:02

算是正式接触到真正的东西了吧 , 大概写了下 , 不是太习惯 , 虽然有了extension , 和// MARK:- 分类注释 , 懒加载也不是太习惯 . 可能是OC敲太多了 , 还不是太适应吧 .


import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{    //懒加载    let tableView:UITableView = {        let tableView = UITableView()        tableView.rowHeight = 100        tableView.estimatedRowHeight = 100        tableView.separatorColor = UIColor.redColor()        return tableView    }()    override func viewDidLoad() {        super.viewDidLoad()        initUI()    }}

// extension + 类名  扩展,将方法抽出封装 (跟OC分类有点像,只能扩充方法,不能扩充属性)// MARK:- 初始化UIextension ViewController {    func initUI() {        //设置frame        tableView.frame = view.bounds        //设置数据源        tableView.dataSource = self        //设置代理        tableView.delegate = self        //添加到view上        view.addSubview(tableView)    }}

// MARK:- 代理方法extension ViewController{    //代理方法    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {        print("当前选中行 - \(indexPath.row)")    }    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {    }}

// MARK:- 数据源方法extension ViewController{    //数据源方法    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return 10    }    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {        let cellID = "cell"        var cell = tableView.dequeueReusableCellWithIdentifier(cellID)        if cell == nil {            //枚举的使用 : 1.枚举类型 + '.' + 具体类型 2.'.'+具体类型            //            cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: cellID)            cell = UITableViewCell(style: .Default, reuseIdentifier: cellID)        }        cell?.textLabel?.text = "嘿嘿嘿-\(indexPath.row)"        return cell!    }}
0 0
原创粉丝点击