[英]Swift autolayout multiple views/labels
我想以編程方式將屏幕分為三個部分。 每個部分應為帶有backgroundColor的標簽,並且寬度設置為:
// Get the device width
self.view.bounds.width
高度必須是動態的。 下圖是一個示例。 每種顏色都是一個部分。 第一部分(紅色部分)必須連接到頂部,而最后一部分(橙色部分)必須連接到底部。 並根據每個部分內部的標簽尺寸來調整高度。
藍色部分始終為100%,並取決於從藍色部分中減去的紅色和橙色部分。
有人對如何實現這一目標有任何想法嗎? 感謝幫助!
為此,最好使用帶有NSLayoutConstraint
。 這是一些示例代碼(目前,這一切都在viewDidLoad
,這可能不是最好的選擇,但我viewDidLoad
自行組織代碼。)
override func viewDidLoad() {
super.viewDidLoad()
// 1.
var topView: UIView = self.view
// Have as many labels as you want!
for i in 0..<numberOfLabels {
let label = UILabel()
// 2.
label.numberOfLines = 0
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(label)
// 3.
if i == 0 || i == numberOfLabels - 1 {
label.setContentHuggingPriority(UILayoutPriority.abs(1000), forAxis: UILayoutConstraintAxis.Vertical)
}
let widthConstraint = NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0)
// 4.
let heightConstraint = NSLayoutConstraint(item: label, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 20.0)
// 5.
let attribute: NSLayoutAttribute = i == 0 ? .Top : .Bottom
let topConstraint = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: topView, attribute: attribute, multiplier: 1, constant: 0)
// 6.
if i == numberOfLabels - 1 {
let bottomConstraint = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)
self.view.addConstraint(bottomConstraint)
}
label.addConstraint(heightConstraint)
self.view.addConstraint(widthConstraint)
self.view.addConstraint(topConstraint)
topView = label
}
}
1. topView
是label
的NSLayoutAttribute.Top
將與之相關的視圖。 例如:第一個標簽的頂部與其容器視圖相關; 第二個標簽的頂部與第一個標簽有關; 第三個標簽的頂部與第二個視圖相關,依此類推。
2.將行數設置為零,以允許label.text
所需的label.text
。
3.將頂部和底部標簽的內容包含優先級設置為1000
。 這將導致頂部和底部標簽“擁抱”文本,因為默認情況下,中間標簽的擁抱優先級為250
。
4.創建一個NSLayoutConstraint
,將label
設置為高於20點,因為要自動設置preferredMaxLayoutWidth
,必須由NSLayoutConstraint
顯式定義標簽的寬度和高度。
5.這將選擇topView
上的屬性,該屬性會將label
到topView
。 例如:如果創建第一個label
,則其頂部將固定在容器視圖的頂部。 否則, label
的頂部將固定在其上方的label
的底部。
6.如果是最后一個標簽,則將其底部邊緣固定在容器視圖的底部。
結果如下:
希望這能回答你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.