user2606782
user2606782

Reputation: 320

Custom TableViewCell autolayout issue upon orientation change

I have a custom UITableViewCell class like this:

class CustomCell: UITableViewCell {
  var mainText:UILabel = UILabel()
  var detailText:UILabel = UILabel()

  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    self.contentView.addSubview(mainText)
    self.contentView.addSubview(detailText)

    self.updateCellConstraints()
  }

  fileprivate func updateCellConstraints() {
    self.mainText.translatesAutoresizingMaskIntoConstraints = false
    self.detailText.translatesAutoresizingMaskIntoConstraints = false
    self.detailText.setContentCompressionResistancePriority(.required, for: .horizontal)

    let margins = self.contentView.layoutMarginsGuide

    self.mainText.leftAnchor.constraint(equalTo: margins.leftAnchor).isActive = true
    self.mainText.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true

    self.detailText.leftAnchor.constraint(equalTo: self.mainText.rightAnchor, constant: 10).isActive = true
    self.detailText.widthAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true
    self.detailText.rightAnchor.constraint(equalTo: margins.rightAnchor, constant: -10).isActive = true
    self.detailText.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true
  }
}

And in cellForRowAtIndexPath I dequeue it and set some custom properties on mainText and detailText and finally set an accessoryType which is a disclosure indictor.

Now the problem. Everything works well in portrait mode but when I switch to landscape on an iPad, my cell is centered (i.e. left and right areas are left blank and cell is centered, maintext and disclosureIndicator are still apart but UI doesn't look good). How do I get rid of this?

I want my cell to work perfectly fine like it is in portrait mode. Am I doing something wrong?

Upvotes: 0

Views: 65

Answers (1)

Ladislav
Ladislav

Reputation: 7283

This is because of readable content guides that Apple added in iOS9.

Just do:

tableView.cellLayoutMarginsFollowReadableWidth = false

or if you deploy to pre iOS9:

if #available(iOS 9.0, *) {
    tableView.cellLayoutMarginsFollowReadableWidth = false
}

More on this topic Readable Width of Table View Cells

Both modes side by side

Upvotes: 2

Related Questions