【问题标题】:Issue with constraints inside a UITableViewCellUITableViewCell 内的约束问题
【发布时间】:2023-03-24 08:55:02
【问题描述】:

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

1) 具有以下约束的 UITextView:

  • 它从单元格的左上角开始
  • 从单元格左侧 + 10 到单元格右侧 - 10。
  • 它的底部应该比下一个元素高 5 点(见下面的 2)

2) 具有以下约束的 UIButton:

  • X 和 Y 以单元格为中心
  • 它从单元格的左侧 + 20 到单元格的右侧 细胞 - 20。
  • 高度为 60

单元格本身的高度定义为 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 中心约束来保留您的建议。

【问题讨论】:

  • answerTextButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true 此行无效,因为您已经指定了前导和尾随约束。您还说单元格的高度为 100,但居中按钮的高度为 60,这没有多大意义,因为您将有 20 个顶部和 20 个左下角,如果您在 textview 和按钮之间需要 5 个空间,你将剩下 15 的 textview 高度,也就是说,你知道的,不多......

标签: ios swift uitableview nslayoutconstraint


【解决方案1】:

复制粘贴。它会工作

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2017-04-21
    • 2020-10-02
    相关资源
    最近更新 更多