ios - 将顶部锚点约束到可选文本视图的底部锚点
问题描述
我有一个标签,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?
解决方案
您可以创建两个约束,然后根据需要激活/停用。
推荐阅读
- python - Python Trio 设置十进制数的工人
- linux - ArchLinux 上的 I2C 用户空间通信
- c++ - 如何使用嵌套初始化构造函数中的一维向量初始化矩阵?
- node.js - 如何在 Mongoose 中保存生日而不引发验证错误
- c - 为什么快速排序函数中的变量“q”在第一个过程(调用)后等于 7
- python - 我可以在 Pandas 中将 getattr 与方法链一起使用吗?
- python - 在 spaCy 中,有没有办法提取提取实体的句子?
- firebase - 收听对象数组流时出现问题来自firestore集合
- c - 回调未在编辑控件上触发
- gcc - 在 Solaris 10 SPARC 中编译 tsocks-1.8