将顶部锚点约束为可选文本视图的底部锚点



我有一个标签,commentLabel和一个textview,statsLabel。它们是包含更多标签(用户名标签,签入名称等(的单元格的一部分。

我想要实现的是将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,但在空时绑定到用户名标签吗?

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

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
}

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

最新更新