相关疑难解决方法(0)

以编程方式添加CenterX/CenterY约束

我有一个UITableViewController,如果没有任何显示,它不会显示任何部分.我添加了一个标签,向用户表明此代码无法显示:

label = UILabel(frame: CGRectMake(20, 20, 250, 100))
label.text = "Nothing to show"
self.tableView.addSubview(label)
Run Code Online (Sandbox Code Playgroud)

但现在,我希望它在水平和垂直方向上居中.通常,我会在屏幕截图中选择突出显示的两个选项(加上高度和宽度的选项):

在此输入图像描述

我尝试了以下代码来添加约束但应用程序崩溃时出现错误:

label = UILabel(frame: CGRectMake(20, 20, 250, 100))
label.text = "Nothing to show"

let xConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterY, multiplier: 1, constant: 0)

label.addConstraint(xConstraint)
label.addConstraint(yConstraint)
Run Code Online (Sandbox Code Playgroud)

错误:

When added to a view, the constraint's items must be descendants of that view (or …
Run Code Online (Sandbox Code Playgroud)

xcode ios autolayout nslayoutconstraint swift

73
推荐指数
5
解决办法
8万
查看次数

标签 统计

autolayout ×1

ios ×1

nslayoutconstraint ×1

swift ×1

xcode ×1