约束UITableViewCell,正确的rightAnchor

时间:2018-09-02 14:15:55

标签: ios uitableview nstablecellview

我需要通过代码以编程方式约束UITableViewCell ...我正在尝试在单元格的containerView内部创建一个子视图,这是实际代码:

contentView.addSubview(testContainerView)

testContainerView.leftAnchor  .constraint(equalTo: contentView.leftAnchor  , constant: 8).isActive = true
testContainerView.topAnchor   .constraint(equalTo: contentView.topAnchor   , constant: 0).isActive = true
testContainerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
testContainerView.rightAnchor .constraint(equalTo: contentView.rightAnchor , constant: 8).isActive = true

但是问题是单元格的宽度似乎超出了屏幕尺寸...我以前从未遇到过此问题。单元格是使用以下方法创建的:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "slotCell") as! SlotTableViewCell2
    cell.setCellDetail(currentSlot: listaSlots[indexPath.row])

    return cell
}

约束条件有问题吗?

这是当前结果的图像:

The orange rect, is the testContainerView

1 个答案:

答案 0 :(得分:1)

您为rightAnchor使用了错误的常量。

尝试以下代码:

contentView.addSubview(testContainerView)
NSLayoutConstraint.activate([
    testContainer.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8.0)
    testContainer.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0.0)
    testContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0.0)
    testContainer.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -8.0)
])

请注意rightAnchor上的负常数。

其他提示:自动布局引擎喜欢在激活所有约束之前先了解所有约束。使用上述方法是配置约束的首选方法

其他提示2:如果您的应用程序被任何RightToLeft语言界面使用,它将被翻转。如果这不是预期的行为,则应使用leadingAnchortrailingAnchor代替leftAnchorrightAnchor

相关问题