У меня есть UITableViewController, который не отображает разделы, если ничего не показывать. Я добавил ярлык, чтобы указать пользователю, что с этим кодом ничего не видно:
label = UILabel(frame: CGRectMake(20, 20, 250, 100))
label.text = "Nothing to show"
self.tableView.addSubview(label)
Но теперь, я хочу, чтобы он был центрирован по горизонтали и по вертикали. Обычно я выбирал два выделенных параметра (плюс один для высоты и ширины) на снимке экрана:
Я попробовал следующий код, чтобы добавить ограничения, но приложение вылетает с ошибкой:
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)
ошибка:
When added to a view, the constraint items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.
2014-12-23 08:17:36.755 [982:227877] *** Assertion failure in -[UILabel _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:], /SourceCache/UIKit/UIKit-3318.16.21/NSLayoutConstraint_UIKitAdditions.m:560
Метка должна всегда располагаться горизонтально и вертикально, поскольку приложение поддерживает поворот устройства.
Что я делаю неправильно? Как успешно добавить эти ограничения?
Спасибо!