带有标题的自定义 UITableViewCell - 约束

Custom UITableViewCell with title - constraints

我有一个自定义的 UITableViewCell,因此

class CustomCell: UITableViewCell {
    private var someCustomView = UIView()

    init(style: UITableViewCell.CellStyle, reuseIdentifier: String?, text: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier) 
      setupContraints()
   }

  required init?(coder: NSCoder) {
     super.init(coder: coder)
  }

  private func setupContraints() {
      contentView.addSubview(someCustomView)

      self.someCustomView.frame.size = CGSize(width: 100, height: 100)

      NSLayoutConstraint.activate([
        self.someCustomView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
        self.someCustomView.topAnchor.constraint(equalTo: contentView.topAnchor)
     ])

    setNeedsLayout()
    layoutIfNeeded()

}

我遇到的问题是关于 NSLayoutConstraint - 忽略这个细节,因为我还没有设置我需要的约束,但是视图只设置框架而不是约束。有什么帮助吗?谢谢!

您需要在添加约束之前将translatesAutoresizingMaskIntoConstraints设置为false,如下所示:

someCustomView.translatesAutoresizingMaskIntoConstraints = false