ios - UITableViewCell 的布局约束未更新
问题描述
我想要达到的效果是让它感觉就像 UITableViewCell 在被选中时“变宽”了。我通过向 UITableViewCell 的内容视图添加一个子视图(我们称之为 visibleView)来做到这一点,然后在选择单元格时调整 mainView。
但是,visibleView 的大小在选择时不会改变。下面的代码:
class feedTableCell: UITableViewCell {
var visibleCell: UIView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = .clear
self.visibleCell = UIView()
self.visibleCell.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(self.visibleCell)
visibleCell.widthAnchor.constraint(equalToConstant: 150).isActive = true
visibleCell.heightAnchor.constraint(equalToConstant: 100).isActive = true
visibleCell.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
visibleCell.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
visibleCell.layer.cornerRadius = 15
visibleCell.backgroundColor = .white
}
override func setSelected(_ selected: Bool, animated: Bool) {
if selected {
self.visibleCell.widthAnchor.constraint(equalToConstant: 300).isActive = true
self.contentView.layoutIfNeeded()
} else {
self.visibleCell.widthAnchor.constraint(equalToConstant: 150).isActive = true
self.contentView.layoutIfNeeded()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
但是,如果我用框架替换布局约束,而是通过调整其框架来更新 visibleCell,一切正常。
解决方案
在添加新的之前,您必须删除以前的宽度限制。它们不被交换。在添加新约束之前,保留对约束的引用以便能够将其删除。
推荐阅读
- python - StandardScaler ValueError: operands could not be broadcast together with shapes (75000,3) (50,) (75000,3)
- javascript - 删除 if 语句
- python - 如何更改列表中的每个元素?
- robotframework - 无法在机器人文件中导入 Selenium2Library
- image-processing - 如何在 Flutter 中从画布上裁剪圆形(或方形或六边形)区域
- javascript - 根据 id 对数组数据进行分组
- angular - 无法将 JSON 数组转换为 HTML 动态表,并且在 Angular 中使用 typescript 显示为空白
- azure-devops - .NET Core 3 构建时间表?
- loopback4 - 如何在 loopback4 中应用搜索 api
- sql - 在 SQL Server 中将 XML 写入驱动器