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

Swift3 如何以编程方式为线添加自动布局约束,swift3,constraints,xcode8,ios-autolayout,Swift3,Constraints,Xcode8,Ios Autolayout,我在yUI中通过编程画了一条线。如何为此行添加约束 let line = UIView(frame: CGRect(x: 10, y: 350, width: 350, height: 1)) line.backgroundColor = UIColor.white;self.view.addSubview(line) NSLayoutConstraint样式 NSLayoutConstraint(item: line, attribute: NSLayoutAttribute.CenterX

我在y
UI
中通过编程画了一条线。如何为此行添加约束

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

NSLayoutConstraint样式

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`

我创建了一条红线:高度=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])
}
结果


感谢您的快速回复。但这并没有对线路进行任何更改。如果我在模拟器中更改了模型,则该行不会出现在同一位置。@tabassumSorry mate。当我尝试您的代码时,我只是得到一个白色屏幕。为什么它不会出现在我身上。让我们复制我的代码并粘贴到ViewDidAppeard方法中。它能工作吗?或者你将行的颜色设置为白色?不。我只是复制粘贴你的代码,完全按照原样粘贴。但我仍然无法获得它。请创建一个新项目并尝试使用我的代码。它能用吗?