首页 > 解决方案 > 将顶部锚点约束到可选文本视图的底部锚点

问题描述

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

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

我在我的单元格(UICollectionViewCell)类中做什么:

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 不知道在哪里进行约束,因为我在单元格类中设置了这样的约束(覆盖初始化):

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

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

标签: iosswiftconstraintssubview

解决方案


您可以创建两个约束,然后根据需要激活/停用。


推荐阅读