如何以编程方式为行添加自动布局约束

时间:2017-03-28 06:03:56

标签: swift3 constraints xcode8 ios-autolayout

我在y UI中以编程方式绘制了一条线。如何为此行添加约束。

let line = UIView(frame: CGRect(x: 10, y: 350, width: 350, height: 1))
line.backgroundColor = UIColor.white;self.view.addSubview(line)

2 个答案:

答案 0 :(得分:2)

我创建了一条红线:高度= 1,顶部= 50,宽度将灵活您可以根据需要修改位置。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let line = UIView()
    line.backgroundColor = UIColor.red
    view.addSubview(line)

    line.translatesAutoresizingMaskIntoConstraints = false

    let leadingConstraint = NSLayoutConstraint(item: line, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 20.0)
    let topConstraint = NSLayoutConstraint(item: line, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 50.0)
    let trailingConstraint = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: line, attribute: .right, multiplier: 1.0, constant: 20.0)
    let heightConstraint = NSLayoutConstraint(item: line, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 1.0)

    view.addConstraints([topConstraint, leadingConstraint, trailingConstraint, heightConstraint])
}

结果!

enter image description here

答案 1 :(得分:1)

NSLayoutConstraint Style

NSLayoutConstraint(item: line, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: line, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0).active = true`