将顶部锚点限制为可选文本视图的底部锚点

Constrain top anchor to bottom anchor of optional textview

我有一个标签 commentLabel 和一个文本视图 statsLabel。它们是包含更多标签(usernameLabel、checkinName、...)的单元格的一部分。

我想要实现的是在 commentLabel 下方显示 statsLabel(其中显示喜欢和评论的数量)。但是,如果 commentLabel 为空,我将其从我的子视图中删除(因为否则标签仍然占用 1 行而没有任何文本,困扰着我的各种自动布局问题)。

我在单元格 (UICollectionViewCell) 中做了什么 class:

contentView.addSubview(commentTextview)
contentView.addSubview(statsLabel)

在我的 cellForItemAt 方法中,我根据数组中的字符串设置了两个项目的文本,如下所示:

if let comment = feed[indexPath.item].commentText {

    cell.commentTextview.text = comment
    if(comment.isEmpty) {

        cell.commentTextview.removeFromSuperview()

    }

}

这很有魅力。 textview 在需要时被移除,并且在有文本时仍然可见。它在有文本时有效,但当它为空(并因此被删除)时,statsLabel 不知道要约束到哪里,因为我在我的单元格 class(覆盖 init)中设置了这样的约束:

statsLabel.topAnchor.constraint(equalTo: commentTextview.bottomAnchor, constant: 2).isActive = true

知道如何确保约束在需要时绑定到 commentTextview,但在它为空时绑定到 usernameLabel 吗?

您可以根据需要创建两个约束,然后 activate/deactivate。

我建议使用堆栈视图,因为它会更容易管理这种行为,但无论如何您都可以将约束设置为变量:

private lazy var topToCommentConstraint: NSLayoutConstraint = {
    let top = statsLabel.topAnchor.constraint(equalTo: commentTextview.bottomAnchor, constant: 2)
    top.isActive = true
    return top
}()

private lazy var topToUsernameConstraint: NSLayoutConstraint = {
    let top = statsLabel.topAnchor.constraint(equalTo: usernameLabel.bottomAnchor, constant: 2)
    top.isActive = false
    return top
}()

if(comment.isEmpty) {

    cell.commentTextview.removeFromSuperview()
    topToCommentConstraint.isActive = false
    topToUsernameConstraint.isActive = true
}