Swift-表格

 //1.创建表格

        let tv = UITableView(frame: view.bounds, style: .Plain)

        

        //2.添加到视图

        view.addSubview(tv)

        

        //3.注册可以使用的cell  [UITableViewCell class] OC

         tv.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellID")

        //4.设置数据源

        //Swift 中没有遵守协议是一个错误

        tv.dataSource = self

       (遵守协议 UITableViewDataSource)

  注:在Swift中没有 @interface ViewController (),因此在  class ViewController: UIViewController , UITableViewDataSource

实现协议方法:

 //MARK:UITableViewDataSource

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

        return 20

    }

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

        let cell = tableView.dequeueReusableCellWithIdentifier("cellID")

        //提示:textLabel 是可选的

        //代码中?是自动带的,如果textLabel有就使用

        cell?.textLabel?.text = "hello world ----\(indexPath.row)"

        return cell!

    

    }

 

posted @ 2017-02-10 12:00  姜晓延  阅读(721)  评论(0编辑  收藏  举报