[英]iOS adding constraints programmatically in Swift
因此,我已经在Xcode
使用了IB
,并且想要在Swift中编写所有UI
。
所以我要做的是:
UIView
来包含我要编写的元素-称之为“ TestView” TestView
作为子视图添加到了VC
。 在TestView
类中,我添加了以下元素:
class TestView: UIView { var someLabel:UILabel! override init(frame: CGRect) { super.init(frame: frame) self.someLabel = UILabel(frame: CGRect(x: self.frame.midX, y: oneSixthHeight, width: 100, height: 22)) self.someLabel.text = "test" var constraints:[NSLayoutConstraint] = [] self.someLabel.translatesAutoresizingMaskIntoConstraints = false let rightsideAnchor:NSLayoutConstraint = NSLayoutConstraint(item: self.someLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 1) constraints.append(rightsideAnchor) NSLayoutConstraint.activateConstraints(constraints) } }
这样,我希望UILabel
可以锚定到视图的右侧。
但是,我确实收到此错误:
由于未捕获的异常“ NSGenericException”而终止应用程序,原因:“无法激活具有>和>的约束,因为它们没有共同的祖先。
约束是否引用了不同视图层次结构中的项目? 那是非法的。
我究竟做错了什么?
仅在将视图添加到视图层次结构后,才应添加约束。 从代码中可以明显看出,您尚未添加要查看的UILabel实例。
为Swift 3更新
import UIKit
class ViewController: UIViewController {
let redView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupAutoLayout()
}
func setupViews() {
view.backgroundColor = .white
view.addSubview(redView)
}
func setupAutoLayout() {
// Available from iOS 9 commonly known as Anchoring System for AutoLayout...
redView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
redView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
redView.heightAnchor.constraint(equalToConstant: 300).isActive = true
// You can also modified above last two lines as follows by commenting above & uncommenting below lines...
// redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
// redView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
约束类型:
/*
// regular use
1.leftAnchor
2.rightAnchor
3.topAnchor
// intermediate use
4.widthAnchor
5.heightAnchor
6.bottomAnchor
7.centerXAnchor
8.centerYAnchor
// rare use
9.leadingAnchor
10.trailingAnchor
etc. (note: very project to project)
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.