将顶部锚点限制到可选textview的底部锚点

时间:2018-09-27 08:35:16

标签: ios swift constraints subview

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

我想要实现的是在studentLabel下方显示statsLabel(其中显示了喜欢和评论的数量)。但是,如果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()

    }

}

这就像一个护身符。文本视图在需要时被删除,并且在有文本时仍然可见。它在有文本的情况下有效,但是当它为空(因此被删除)时,statsLabel不知道要限制在哪里,因为我在单元格类中设置了这样的约束(覆盖init):

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

有什么想法可以确保约束在需要时绑定到commentTextview,而在空时绑定到usernameLabel吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我建议使用堆栈视图,因为这样可以更轻松地管理这种行为,但是无论如何您都可以将约束设置为变量:

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
}