A custom view is located in IB by dragging UIView object from library and it's class name is set to the custom view class name. This custom view has a subview, which is added in init?(coder aDecoder: NSCoder)
.
How should anchor type constraints be composed, and where should they be located so the _centralLabel subview is set centrally in the custom view, and it's dimensions are 25% of the custom's view dimensions?
If the code is written like this:
override func updateConstraints() {
if !_subviewsConstraintsAdded {
_centralLabel.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.25).isActive = true
_centralLabel.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.25).isActive = true
_centralLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
_centralLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
_subviewsConstraintsAdded = true
}
super.updateConstraints()
}
The result of the code is, that instead of setting the size of _centralLabel to be 25% of the custom view, the custom view is shrunk to (0,0) which is the size of _centralLabel while updateConstraints() is being called.
The missing bit was that:
_centralLabel.translatesAutoresizingMaskIntoConstraints = false
which should be located somewhere after programmatically instantiating the subview with this line:
_centralLabel = UILabel()
After this correction the _centralLabel subview has enlarged and has moved to the center of the view, while the view itself remained in its original size, shape and position.