swift - NSLayoutConstraints : How do you correctly center a subview within a view?

标签 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>"
)

我不确定我做错了什么。我只是在 UIButton 的 subview “UILabel”中添加了一个 Vertical & Horizo​​ntal 约束。

最佳答案

尝试添加

label.translatesAutoresizingMaskIntoConstraints = NO

到代码的顶部

关于swift - NSLayoutConstraints : How do you correctly center a subview within a view?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841792/

相关文章:

ios - Autolayout - 设置框架宽度和宽度作为约束之间的差异

sql - 表列的顺序约束

ios - UILongPressGestureRecognizer 被解雇了两次

ios - 尝试使用插图隐藏 UITableViewCell 分隔符,但它只会降低不透明度

ios - MPNowPlayingInfoCenter nowPlayingInfo 在轨道结束时不更新

ios - 如何在 Xcode 6 中使用 AutoLayout 创建动态大小的分页水平 UIScrollView

swift - self 调整特定的 UITableView 单元格

sql - 将记录输入 Access 表时应用约束的数据宏(触发器)

grails - 条目创建中的域类约束

ios - 快速上传图像到FTP服务器