ios - 添加 subview 并以编程方式使用约束定位它

标签 ios swift uiview uilabel autolayout

我在 View Controller 上使用 IB 添加了一个 UIView。我们称它为 redView

enter image description here

然后我在代码中使用自动布局约束固定了它的所有四个边,当我运行它时,它看起来像预期的那样。

enter image description here

现在我想以编程方式向此 View 添加一个 UILabel 并使用自动布局约束将其定位在中心。

下面是我到目前为止的代码。

import UIKit

class ViewController: UIViewController {

    @IBOutlet private var redView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        redView.setTranslatesAutoresizingMaskIntoConstraints(false)

        let leadingConstraint = NSLayoutConstraint(item: redView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)
        let trailingConstraint = NSLayoutConstraint(item: redView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)
        let topConstraint = NSLayoutConstraint(item: redView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: redView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
        view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])


        let label = UILabel()
        label.text = "Auto Layout Exercise"
        redView.addSubview(label)

        let xCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: redView, attribute: .CenterX, multiplier: 1, constant: 0)
        let yCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: redView, attribute: .CenterY, multiplier: 1, constant: 0)
        let leadingConstraint1 = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: redView, attribute: .Leading, multiplier: 1, constant: 20)
        let trailingConstraint1 = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: redView, attribute: .Trailing, multiplier: 1, constant: -20)
        redView.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])

    }

}

问题是标签没有出现在 redView 上。谁能告诉我这里缺少什么?

谢谢。

最佳答案

我很确定你还需要设置:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

否则我认为约束不会应用于标签。

关于ios - 添加 subview 并以编程方式使用约束定位它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26721920/

相关文章:

iphone - UIAnimation - 从 button.frame.origin.y 显示 UIView

ios - 从 Swift 初始化 obj viewcontroller 时未调用 viewDidLoad

ios - 从 iOS 9 中的深层链接返回时更新 UI

arrays - 无法将 "find()"方法与 UIView 类型的数组一起使用

启用绘图的 iOS 四舍五入 UIView 角

ios - SPOJ swift - NZEC

iphone - [NSString stringByReplacingOccurrencesOfString : @"""withString: @""""];

uiview - systemLayoutSizeFittingSize : require setNeedsLayout & layoutIfNeeded before it?

ios - SwiftUI |使用 ScrollViewReader 为 scrollTo() 自定义动画?

ios - 使用 AutoLayout 调整 UIScrollView 内的 UIView 大小以进行滚动?