我認爲這將是一個有趣的練習,所以我創建一個小測試項目。代碼的要點如下。您可以將其複製/粘貼到標準的Single View iOS模板中。
(請注意,我用SnapKit對程序自動佈局,因爲它是如此之比的UIKit API簡單得多。我覺得它甚至比在Xcode做的事情要簡單得多。)
結果是完全一樣的馬特偉大的截屏。
// ViewController.swift
import UIKit
import SnapKit
class ViewController: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
let leftLabel = UILabel()
leftLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "addText:"))
leftLabel.userInteractionEnabled = true
view.addSubview(leftLabel)
leftLabel.numberOfLines = 0
leftLabel.text = "All the world's a stage, and all the men and women merely players: they have their exits and their entrances; and one man in his time plays many parts, his acts being seven ages."
leftLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(40)
make.left.equalTo(self.view)
make.right.equalTo(self.view.snp_centerX)
}
let rightLabel = UILabel()
rightLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "addText:"))
rightLabel.userInteractionEnabled = true
view.addSubview(rightLabel)
rightLabel.numberOfLines = 0
rightLabel.text = "There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures."
rightLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(40)
make.right.equalTo(self.view)
make.left.equalTo(self.view.snp_centerX)
}
let bottomView = UIView()
view.addSubview(bottomView)
bottomView.backgroundColor = UIColor.redColor()
bottomView.snp_makeConstraints { (make) -> Void in
make.height.equalTo(20)
make.left.right.equalTo(self.view)
make.top.greaterThanOrEqualTo(leftLabel.snp_bottom)
make.top.greaterThanOrEqualTo(rightLabel.snp_bottom)
}
}
@objc func addText(recognizer: UIGestureRecognizer) {
if let label = recognizer.view as? UILabel {
label.text = label.text! + " I like cheese."
}
}
}
更新了代碼以在點擊時向標籤添加一些額外的文本。
像甲約束「對象A應該是對象B低於N個點」是在自動佈局極其簡單。你能展示一些你先試過的代碼嗎? –
是的,但我希望對象A是低於具有更高高度的那個N點,比如說對象B和對象C在同一行中,但它們的高度不固定(像一些動態文本),我想要對象A在比較高的對象下面N個點。 –
你可以把Label1和Label2放在一個NSView中,它會隨着標籤一起變大嗎?然後,但在NSView下的Label3? –