NSLayoutConstraints:如何在视图中正确居中子视图?

时间:2015-03-03 21:00:48

标签: swift autolayout constraints

问候语:

我试图将UILabel' 1'在绿色按钮内。

enter image description here

    这是我的代码:

let dayFrame = CGRectMake(1, 1, 16, 16)
let myLabel1 = UILabel(frame:dayFrame)
myLabel1.font = calFont

myLabel1.tag = 100
dayButton1.addSubview(myLabel1)

var viewDictionary:Dictionary = ["myLabel": myLabel1]

dayButton1.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
    "H:|[myLabel]|",
    options:nil, metrics:nil,
    views:viewDictionary))
dayButton1.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
    "V:|[myLabel]|",
     options:nil, metrics:nil,
     views:viewDictionary))

但是我遇到了以下运行时错误:

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) 
(
    "<NSIBPrototypingLayoutConstraint:0x7fbebae37010 'IB auto generated at build time for view with fixed frame' H:[UIButton:0x7fbebae47ac0(28)]>",
    "<NSLayoutConstraint:0x7fbebacb5fc0 H:|-(0)-[UILabel:0x7fbebae9aa00'1']   (Names: '|':UIButton:0x7fbebae47ac0 )>",
    "<NSLayoutConstraint:0x7fbebacd68a0 H:[UILabel:0x7fbebae9aa00'1']-(0)-|   (Names: '|':UIButton:0x7fbebae47ac0 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7fbebc421b70 h=--& v=--& UILabel:0x7fbebae9aa00'1'.midX == + 9>"
)

我不确定我做错了什么。我只是添加了一个垂直&amp;对UIButton子视图的水平约束,&#39; UILabel&#39;一定的维度。

2 个答案:

答案 0 :(得分:1)

尝试添加

label.translatesAutoresizingMaskIntoConstraints = NO

到代码顶部

答案 1 :(得分:1)

根据反馈...... 我得到了正确的解决方案:

myLabel1.setTranslatesAutoresizingMaskIntoConstraints(false)