【问题标题】:how can I add auto layout constraints for a line programatically如何以编程方式为一行添加自动布局约束
【发布时间】:2017-03-28 06:03:55
【问题描述】:

我以编程方式在 y UI 中画了一条线。如何为这条线添加约束。

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

【问题讨论】:

    标签: swift3 constraints xcode8 ios-autolayout


    【解决方案1】:

    我创建了一条红线:height = 1, top = 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])
    }
    

    结果!

    【讨论】:

    • 对不起伙计。我在尝试你的代码时只是得到一个白屏。为什么它不适合我。
    • 复制我的代码并粘贴到 viewDidAppear 方法中。有效吗?
    • 或者你将线条的颜色设置为白色?
    • 没有。我只是照原样复制粘贴你的代码。但我还是没有得到它
    • 让我们创建一个新项目并尝试使用我的代码。它会起作用吗?
    【解决方案2】:

    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`
    

    【讨论】:

    • 感谢您的快速回复。但这并没有对线路进行任何更改。如果我在模拟器中更改模型,则该行不会出现在同一个地方。@tabassum
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2015-12-26
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多