简体   繁体   中英

UITableView in Swift - dequeueing of cells

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    return 5
}

func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
        let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell

        println("ip: \(indexPath.row)")
        cell.bookLabel.text = "Row #\(indexPath.row)"

        return cell
    }

I just see one cell, with the text overwritten 5 times, instead of 5 cells. I thought we didn't have to do the if (!cell) nonsense anymore? What am I doing wrong?

If you are seeing the UILabels overwritten 5 times, it is because your cell height has not been defined and it is being computed as 0 pixels tall. Any one of the following should help you explicitly or implicitly define the row height:

1) Set the row height within Interface Builder:

在此处输入图片说明

2) Implement the UITableViewDataSource protocol method:

func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    return 50.0
}

3) Set Auto Layout constraints between your cell's UILabel and the outer boundaries of the UITableViewCell :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM