Я создаю свой собственный класс с наследниками от UIView, class MyView: UIView {
Идея состоит в том, чтобы создать представление и добавить в него некоторую метку.Я добиваюсь этого путем:
init() {
super.init(frame: CGRect(x: 8.0, y: 104.0, width: UIScreen.main.bounds.width - 16.0, height: 60.0))
initialize()
}
, где
fileprivate func initialize() {
label = UILabel()
label.numberOfLines = 0
label = UILabel(frame: CGRect(x: 16.0, y: 8.0, width: self.frame.width - 32.0, height: self.frame.height - 16.0))
self.addSubview(label)
}
, и пока все работает отлично.Но теперь я хочу сделать динамическую высоту этого пользовательского вида, поэтому высота моего вида будет зависеть от высоты (текста) метки в нем.
Я пытался добавить:
let constraints = [
NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 8.0),
NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 8.0)]
label.addConstraints(constraints)
и
self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true
и в итоге я получаю огромную ошибку в журналах с:
The view hierarchy is not prepared for the constraint
When added to a view, the constraint's 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.
Может кто-нибудь помочь мне с этой проблемой?Я прогуглил это, но не смог найти ничего, что помогло бы мне решить мою проблему.Возможно я делаю свои макеты неправильно.Я буду признателен за вашу помощь!