gpt4 book ai didi

ios - 为什么 NSLayoutConstraints 被忽略?

转载 作者:行者123 更新时间:2023-12-01 17:51:15 24 4
gpt4 key购买 nike

我对 iOS 布局约束机制存在误解。请参阅下面列出的我放置在 viewDidLoad 中的代码。

    var btn = UIButton()
btn.setTitle("i am a button", forState: UIControlState.Normal)
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
btn.backgroundColor = UIColor.lightGrayColor()
btn.sizeToFit()

view.addSubview(btn)

view.addConstraint(
NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: btn,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1.0,
constant: 0.0))

view.addConstraint(
NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: btn,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1.0,
constant: 0.0))

看来我的意图很明确。我想在设备屏幕的中央看到一个按钮。但我只能看到下面的图片。

iPhone 6 Simulator

我在项目控制台中有一个输出,非常可怕,我无法从中理解任何内容。

Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", " (Names: '|':UIWindow:0x7fd318551080 )>" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful. 2015-04-28 23:46:04.516 ConsTest[5966:248434] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", " (Names: '|':UIWindow:0x7fd318551080 )>" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.

看起来这些约束被视为矛盾的,因此根本被忽略了。我无法真正指出为什么我不能创建一个按钮并以编程方式将其放置在中心。非常感谢任何相关指示。

最佳答案

在你的 UIButton (btn) 上设置translatesAutoresizingMaskIntoConstraints = false

例如

btn.translatesAutoresizingMaskIntoConstraints = false

推荐阅读:Adopting Auto Layout

关于ios - 为什么 NSLayoutConstraints 被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29928889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com