首页 > 解决方案 > 方向更改时的自定义 TableViewCell 自动布局问题

问题描述

我有一个这样的自定义 UITableViewCell 类:

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
  }
}

cellForRowAtIndexPath我将它出列并设置一些自定义属性mainTextdetailText最后设置一个accessoryType作为披露指标的。

现在的问题。在纵向模式下一切正常,但是当我在 iPad 上切换到横向时,我的单元格居中(即左右区域留空,单元格居中,maintext并且disclosureIndicator仍然分开,但 UI 看起来不太好)。我该如何摆脱这个?

我希望我的手机能够像在纵向模式下一样正常工作。难道我做错了什么?

标签: iosswiftuitableviewautolayout

解决方案


这是因为 Apple 在 iOS9 中添加了可读的内容指南。

做就是了:

tableView.cellLayoutMarginsFollowReadableWidth = false

或者如果您部署到 iOS9 之前:

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

更多关于这个主题的表格视图单元格的可读宽度

两种模式并排


推荐阅读