您需要以下VFL字符串爲您的標籤:
- 將每個標籤在40pt從頂部每個標籤需要:
"V:|-40-[*labelName*]"
。將40
更改爲最適合您的任何內容。
- 要放置標籤彼此相鄰並設置其寬度你需要這個單一VFL字符串:
"H:|-[label0(50)][label1(40)][label2(70)][label3(30)][label4(20)][label5(10)][label6(30)]"
爲了能夠使用你的視覺格式語言創建一個包含所有標籤的字典。該字典的值是UILabels
,鍵是Strings
,您可以在VFL字符串中使用它來定義應將約束添加到哪個標籤。在這種情況下,我用鑰匙「label0」,「LABEL1」,「標籤2」等
下面是一個例子你怎麼可以在循環中添加的約束:
let labelWidths = [50, 40, 70, 30, 20, 10, 30]
var labels = [String: UILabel]()
var allConstraints = [NSLayoutConstraint]()
var horizontalConstraintsString = "H:|-"
for i in 0..<7 {
let labelName = "label\(i)"
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
// set text, textColor etc.
view.addSubview(label)
labels[labelName] = label
// add vertical constraints to label
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-40-[\(labelName)]", options: [], metrics: nil, views: labels)
allConstraints.appendContentsOf(verticalConstraints)
// add label to horizontal VFL string
horizontalConstraintsString += "[\(labelName)(\(labelWidths[i]))]"
}
// get horizontal contraints from horizontal VFL string
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontalConstraintsString, options: [], metrics: nil, views: labels)
allConstraints.appendContentsOf(horizontalConstraints)
NSLayoutConstraint.activateConstraints(allConstraints)
UPDATE: 正如你在你的評論中寫道,它仍然不適合你,這裏是我的示例項目中的完整ViewController
類。因此,只要在Xcode中創建一個新項目,將以下代碼粘貼到ViewController
類:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGrayColor()
let labelWidths = [50, 40, 70, 30, 20, 10, 30]
var labels = [String: UILabel]()
var allConstraints = [NSLayoutConstraint]()
var horizontalConstraintsString = "H:|-"
for i in 0..<7 {
let labelName = "label\(i)"
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "\(i)"
label.layer.cornerRadius = 6
label.clipsToBounds = true
label.backgroundColor = UIColor.grayColor()
view.addSubview(label)
labels[labelName] = label
// add vertical constraints to label
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-40-[\(labelName)]", options: [], metrics: nil, views: labels)
allConstraints.appendContentsOf(verticalConstraints)
// add label to horizontal VFL string
horizontalConstraintsString += "[\(labelName)(\(labelWidths[i]))]"
}
// get horizontal contraints from horizontal VFL string
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontalConstraintsString, options: [], metrics: nil, views: labels)
allConstraints.appendContentsOf(horizontalConstraints)
NSLayoutConstraint.activateConstraints(allConstraints)
}
}
我加了背景顏色和圓角半徑的標籤,所以你可以看到其中一個標籤結束和下一個開始。當你運行這個項目,你應該看到以下內容:
謝謝你這麼much.But它顯示nothing.In獨立的Xcode項目我複製這viewDidLoad中和的聲明是viewdidload.And上面我添加背景顏色來標記。運行時甚至沒有顯示 – Lydia
我將我的ViewController類添加到我的答案中。它確實有效,所以你可以使用它來找出爲什麼它仍然不能在你的項目中工作。 – joern
工作過,謝謝 – Lydia