如何以编程方式添加动态宽度约束

时间:2017-02-18 16:51:32

标签: ios swift uiview autolayout nslayoutconstraint

我是iOS开发的新手。我想构建没有storyboard或xib / nib的布局。所以我试图以编程方式添加约束。 我已经搜索了一些关于以编程方式添加约束的教程。但是视图无法正确显示。

我在ViewController类中尝试此代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let testView = UIView()
    self.view.addSubview(testView)

    // Add Constraints
    self.view.translatesAutoresizingMaskIntoConstraints = false
    testView.translatesAutoresizingMaskIntoConstraints = false

    let top = NSLayoutConstraint(item: testView, attribute: .top, relatedBy: .equal
        , toItem: self.view, attribute: .top, multiplier: 1, constant: 50.0)
    let bottom = NSLayoutConstraint(item: testView, attribute: .bottom, relatedBy: .equal
        , toItem: self.view, attribute: .bottom, multiplier: 1, constant: -50.0)
    let leading = NSLayoutConstraint(item: testView, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50.0)
    let trailing = NSLayoutConstraint(item: testView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -50.0)
    self.view.addConstraints([top, bottom, leading, trailing])
}

通常,他们不需要在教程中定义视图的大小或有关宽度和高度的约束。但是可以在他们的教程中显示视图。在我的情况下,我的 testView 无法在应用中显示它,甚至已经设置了top,bottom,leading和trailing约束。我错过了什么吗?问题是什么?

其中一个教程: http://www.knowstack.com/swift-nslayoutconstraint-programatically-sample-code/

编辑: 让我解释一下。我想创建一个适用于通用设备的UIViewUIView具有constant: 10的上限,下限,前导和尾随约束。因此,我不需要设置UIView的大小。

Expected Result (I am using draw tool to simulate the result)

2 个答案:

答案 0 :(得分:2)

这是屏幕底部视图约束的示例,高度等于80:

var yourView = UIView()
yourView.translateAutoresizingMaskIntoConstraints = false
yourSuperView.addSubview(yourView)

// Pin the leading edge of yourView  to the leading edge of the main view
yourView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true

// Pin the trailing edge of yourView to the leading trailing edge
yourView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true

// Pin the bottomedge of yourView to the margin's leading edge
yourView .bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true

// The height of your view
yourView.heightAnchor.constraintEqualToConstant(80).active = true

答案 1 :(得分:0)

您有两个问题:

  1. 请勿设置self.view.translatesAutoresizingMaskIntoConstraints = false。您只需为要添加的子视图设置translatesAutoresizingMaskIntoConstraints

  2. 您正在使用.greaterThanOrEqual约束而不是.equal约束。这样做的问题是会留下很多摆动空间,并且您获得的值会导致testView宽度为0。如果您更改为.equal,则会正确约束值。