ios - 如何以编程方式添加具有动态宽度的约束

标签 ios swift uiview autolayout nslayoutconstraint

<分区>

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

我正在我的 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])
}

通常,他们不需要在教程中定义 View 的大小或关于宽度和高度的约束。但是 View 可以显示在他们的教程中。在我的例子中,即使设置了顶部、底部、前导和尾随约束,我的 testView 也无法在应用程序中显示它。我错过了什么吗?有什么问题?

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

编辑: 让我解释更多。我想创建一个适用于通用设备的 UIViewUIView 具有 constant: 10 的顶部、底部、前导和尾随约束。所以,我不需要设置 UIView 的大小。

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

最佳答案

这是一个 View 约束到高度等于 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

关于ios - 如何以编程方式添加具有动态宽度的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42317926/

相关文章:

ios - 如何在不进入无限循环的情况下调配 NSError init

Swift:如何定义具有无主(不安全)引用的 UIView 委托(delegate)?

swift - 如何在 UIView 中居中放置多个元素

ios - 为什么界面生成器不允许我将 uiview 添加到 uitableview ?

ios - 无法在SDK 3.2中保存Facebook accessToken

iOS 应用程序在删除部分中的最后一个单元格后崩溃

ios - 在显示来自 viewDidload 的警报之前显示来自应用程序委托(delegate)的警报

iphone - 在不需要的 View 中触发替代景观

swift - 在 Swift 中重新创建 Functor 类型

ios - 如何在没有 Stroybord/Xib 的情况下使用 JTCalendar