简体   繁体   中英

Custom UITableViewCell does not size properly when Accessory is added

I'm having trouble getting a custom UITableViewCell to size properly when an Accessory is set. Why does the Accessory blow the cell sizing up on the initial display? When I scroll, with the accessory set, the sizing corrects itself - however, the initial view is not sizing correctly.

I've watched the WWDC14 (what's new in tableview) video several times and I've read many stackoverflow questions and tried many solutions. I think I have most of the problem solved - cells do resize for dynamic text - but I'm stumped on this strange initial behavior. I am running XCode 6.1.1 deploying to iOS 8.1.

I'm using a storyboard. I have a UITableViewController and custom UITableViewCell. I define constraints in the storyboard and there are no constraint warnings and I see no constraint messages in the console at runtime.

In my UITableViewController viewDidLoad()

tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension

with override

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell", forIndexPath: indexPath) as TableViewCell

    cell.configure(titles[indexPath.row])

    return cell
}

This is my entire custom UITableViewCell

class TableViewCell: UITableViewCell {

@IBOutlet weak var titleLabel: UILabel!

func configure(title: NSString) {
    titleLabel.text = title
    titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
}

override func layoutSubviews() {
    super.layoutSubviews()
    titleLabel.preferredMaxLayoutWidth = frame.width
}

}

This is what it looks like when Accessory None is set on the cell

在此处输入图片说明

This is what it looks like when I set Accessory Disclosure Indicator on the cell

在此处输入图片说明

Again, when I scroll with the accessory set the sizing corrects itself. I've tried adding a vertical constraint to the cell both in storyboard and also by adding all constraints programmatically with no success. Thank you for any thoughts.

I've seen this problem too with storyboard designed self-sizing cells. Try adding self.layoutIfNeeded() to an override of didMoveToSuperview in your cell class. I don't know if this is a bug, or we're just missing something that we're supposed to be doing.

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