ios - 以编程方式添加的约束不起作用

标签 ios swift constraints

我一直在尝试以编程方式将约束添加到 View 中,我也以编程方式将约束添加到 View Controller 中。然而,似乎没有遵守这些限制。

该 View 已添加到 View Controller 的 Storyboard中,但直到稍后才真正添加到 View Controller 的 View 中(请参见下面的屏幕截图)。

enter image description here

我尝试添加各种约束,但到目前为止没有一个起作用。我现在已将其简化为下面的单个约束,但即使这样也行不通。我做错了什么?

@IBOutlet var loadingView: LoadingView!

override func viewDidLoad() {
    super.viewDidLoad()
    displayLoadingView(true)
}

func displayLoadingView(display: Bool) {
    if display {
        view.addSubview(loadingView)

        let widthConstraint = NSLayoutConstraint(item: loadingView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50.0)

        view.addConstraint(widthConstraint)
    }
}

最佳答案

translatesAutoresizingMaskIntoConstraints = false 设置为您以编程方式设置约束的任何 View 。

来自 apple doc :
将AutoresizingMaskIntoConstraints 转换为

If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.

关于ios - 以编程方式添加的约束不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122549/

相关文章:

ios - Instagram hooks 预选媒体问题

ios - CTFontGetAscent() 与 OSX 上匹配字体的 ascent 有很大不同

ios - CoreML 中的二元分类模型训练

ios - 延迟沿着 BezierPath 动画 UIView

oracle - 当我不知道约束的名称时,如何在 Oracle 中删除 "not null"约束?

iphone - 如何在 iPhone 上对 Box2D 场景进行 "render"

swift - 如何获取 UICollectionView 中每个选定单元格的按钮标题?

ios - Firestore - 查询引用字段

ios - Xcode 5.1 : Where have the delta iOS 6/7 settings gone?

c# - 接口(interface)的对象,但对实现接口(interface)的类型有约束