UITableViewCell 内部的约束问题

Issue with constraints inside a UITableViewCell

我有一个 UITableView 的自定义单元格。我想要单元格中的以下元素:

1) 具有以下约束的 UITextView:

2) 具有以下约束的 UIButton:

单元格本身定义为高度 100。

然而,根据我得到的错误,我的约束似乎有一些冲突,但我看不到在哪里。这是我的代码:


// constraints for the UIButton

answerTextButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
answerTextButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
answerTextButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true
answerTextButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
answerTextButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true


// constraints for the UITextView
answerTextView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
answerTextView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
answerTextView.topAnchor.constraint(equalTo: topAnchor).isActive = true
answerTextView.bottomAnchor.constraint(equalTo: answerTextButton.topAnchor, constant: -5).isActive = true

这里有什么冲突?

谢谢。

编辑:我不相信我的错误。虽然您认为 X 中心约束没有用,但这不是问题所在。问题是……我忘了添加 "answerTextView.translatesAutoresizingMaskIntoConstraints = false"。 对不起,以前从未发生过!因此,基本上我对 UITextView 的所有约束都因此而变得混乱。添加它可以解决所有问题,但我保留了您的建议,删除了 UIButton 上的 X 中心约束。

复制粘贴。它会起作用

       // constraints for the UIButton

    answerTextButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
    answerTextButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
    answerTextButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true
    answerTextButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true


      // constraints for the UITextView
    answerTextView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
    answerTextView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
    answerTextView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    answerTextView.bottomAnchor.constraint(equalTo: answerTextButton.topAnchor, constant: -5).isActive = true