TableView中cell的使用

2016-10-12  本文已影响11人  Dove_Q
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //第一种注册Cell类型的方法
//        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
//        tableView.dataSource = self
//        tableView.delegate = self
    }

    @IBAction func didShowList(sender: UIButton) {
        tableView.hidden = false
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //编译预处理指令
#if false
    //第一种创建Cell的方式
    //只能获取空闲的Cell,如果没有获取到,返回nil
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
        }
#else
        //第二种创建的方式
    //获取空闲的Cell,如果没有获取到,根据重用标识自动创建Cell对象
    let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
#endif
        
        cell?.textLabel?.text = "A"
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
        
        tableView.hidden = true
    }
}
上一篇下一篇

猜你喜欢

热点阅读