假设 CustomView 的
大小为 300x300。 iconImageView
有它的大小和分配的约束。我不知道 UILabel
中的文本要多长时间,所以我不想使 UILabel
的大小保持不变。我的目标是将左约束固定到 iconImageView
的右侧,将右约束固定到 customView
。
override func updateConstraints() {
super.updateConstraints()
iconImageView.snp.updateConstraints { (make) in
make.left.equalTo(customView).offset(10)
make.centerY.equalTo(customView)
make.size.equalTo(CGSize(width: 40.0, height: 40.0))
}
nameLabel.snp.updateConstraints { (make) in
make.right.equalTo(customView).offset(-10)
make.left.equalTo(iconImageView.snp.right).offset(10)
make.centerY.equalTo(customView)
}
}
当我尝试此方法时出现错误:无法同时满足约束。
执行此操作的正确方法是什么?
最佳答案
好吧,我想您的 subview 对顶部/底部约束一无所知,这意味着 View 不知道如何重新布局自身。试试这个:
override func updateConstraints() {
super.updateConstraints()
iconImageView.snp.updateConstraints { (make) in
make.left.equalTo(customView).offset(10)
make.centerY.equalTo(customView)
// Also from my point of view this line \/
// is not very readable
// make.size.equalTo(CGSize(width: 40.0, height: 40.0))
// Changed to:
make.width.height.equalTo(40.0)
}
nameLabel.snp.updateConstraints { (make) in
make.right.equalTo(customView).offset(-10)
make.left.equalTo(iconImageView.snp.right).offset(10)
// Add:
make.top.equalTo(customView.snp.top)
make.bottom.equalTo(customView.snp.bottom)
}
}
如果您想保持标签的“默认”高度(在空字符串等情况下),您可以添加:
make.height.greaterThanOrEqual(40.0)
自动布局和框架也不能很好地相互配合,所以你应该在“updateConstraints”方法中布局你的自定义 View ,类似于:
customView.snp.updateConstraints { (make) in
make.edges.equalTo(self)
}
关于swift - 使用 SnapKit 自动调整 UILabel 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419393/