我认为这将是一个有趣的练习,所以我创建一个小测试项目。代码的要点如下。您可以将其复制/粘贴到标准的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? –