![](/img/trans.png)
[英]iOS - How to set constraints such that the bottom of a label will be equal to an image view but the height can vary
[英]How to Set constraints for UILabels programmatically Where Label Count is equal to Main screen Height in Swift
我想创建这个格式
label 1 | label 2 | label 3 | label 4
label 5| label 6| label 7|
其中标签Count等于View Height。 并且还想设置约束。 下面的代码是Create UILabels:
for i in 0...Int(self.view.frame.height)
{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
label.textAlignment = NSTextAlignment.center
label.text = "label"
label.sizeToFit()
self.view.addSubview(label)
}
它看起来你想在每一行堆叠4个标签。
如果您支持iOS> 9.0,请使用UIStackView
。
否则,您必须计算每行标签之间的间距:
let spacing = (screenWidth - (w1 + w2 + w3+ w4))/5
并使用.addConstraints
以编程方式添加约束。
更好的方法是使用Visual格式语言但我无法帮助你解决VFS的上下文,因为我个人不使用它。
但是如果你想用NSLayoutConstraint来做,那么它可以用一种非常简单的方式完成。
我不是在编写确切的代码,但会向您解释如何解决这个问题。
注意 - 不要忘记设置translatesAutoresizingMaskIntoConstraints = false
并且不要忘记在要保持活动的所有约束上设置isActive = true。
因为如果你忘记这样做,那么你的代码将不起作用😅
然后将左侧label1
与父视图对齐,您可以通过锚点或NSLayoutConstraints执行此操作。我建议您使用Anchor执行此操作。
label1.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 0).isActive = true
然后将其他标签的前缘与前一个的前缘对齐,如 -
label2.leadingAnchor.constraint(equalTo: label1.leadingAnchor, constant: 0).isActive = true
最后,将最右边的标签与父视图的后缘对齐,如 -
rightMostLabel.trailingAnchor.constraint(equalTo: parentView.trailingAnchor, constant: 0).isActive = true
然后设置label1相对于父视图的顶部对齐方式
label1.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 0).isActive = true
然后最后设置所有标签的宽度等于任何一个标签。 比方说,我们将所有标签的宽度设置为等于label1。 通过-
NSLayoutConstraint(item: label1, attribute: .width, relatedBy: .equal, toItem: label2, attribute: .width, multiplier: 1, constant: 0).isActive = true
上面的代码是label1和label2,你必须用label2和label3再做一遍,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.