Here are some examples of how the methods are used:
updateConstraints()
Override this method when you want a UIView
subclass to specify constraints for your subviews.
class AView: UIView {
var yaAgregoConstraints = false
override func updateConstraints() {
print(#function)
if yaAgregoConstraints == false {
yaAgregoConstraints = true
addConstraint(NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 60))
addConstraint(NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 60))
}
super.updateConstraints()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let aView = AView()
aView.backgroundColor = UIColor.redColor()
aView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(aView)
}
setNeedsLayout()
and layoutIfNeeded()
Continuing the previous example, let's say we want to know the
view size% co_of% after creating it. We add this to
end of aView
:
override func viewDidLoad() {
super.viewDidLoad()
...
print(aView.frame)
}
Print:
(0.0, 0.0, 0.0, 0.0) // esto es incorrecto!
updateConstraints() // lo que hace print(#function)
Print a size of zero because after creating the view viewDidLoad()
, it has constraints, but they have not yet been calculated so that aView
has a size (a layout pass, which gives size to aView
, a a little later). If we already want its size to be calculated, we invoke these methods before requesting the size at aView
:
override func viewDidLoad() {
super.viewDidLoad()
...
aView.setNeedsLayout()
aView.layoutIfNeeded()
print(aView.frame)
}
Print:
updateConstraints() // ahora updateConstraints se ejecuta primero
(0.0, 0.0, 60.0, 60.0) // y el tamaño es correcto
aView
and setNeedsUpdateConstraints()
The system calls the updateConstraintsIfNeeded()
method in each layout-pass (every certain amount of milli-seconds). Call the default implementation of updateConstraints()
or the implementation that we specify. To cut this wait from the layout-pass and have the system call updateConstraints()
, invoke the methods like this:
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
updateConstraints()
updateViewConstraints()
is equivalent to updateViewConstraints()
, but is a method of setNeedsUpdateConstraints()
, not UIViewController
, how the previous methods.
More information: link