Suppose I have created a subclass of UIView
to make a custom UI component and I have another view inside my custom view.
Here's the code
class CustomView : UIVIew{
private var innerView : UIView!
convenience init(){
self.init(frame : CGRectZero);
}
override init(frame : CGRect) {
super.init(frame : frame);
self.innerView = UIView();
/*
* The following code is the frame I want to set
for my innerView evertimes iOS layouts my CustomView
by means of NSLayoutConstraint because writing
NSLayoutConstraint programmatically is time consuming.
* The Question is where to put this code ?
Inside layoutIfNeeded() or layoutSubviews
*/
let myDesiredWidth = self.frame.size.width * 0.8;
let myDesiredHeight = self.frame.size.height * 0.8;
let myDesiredX : CGFloat = (self.frame.size.width - myDesireWidth) / 2
let myDesiredY : CGFloat = (self.frame.size.height - myDesireHeight) / 2;
let myDesireFrame : CGRect = CGRectMake(myDesiredX, myDesiredY, myDesiredWidth, myDesiredHeight);
self.innerView.frame = myDesireFrame;
}
override func layoutSubviews(){
}
override func layoutIfNeeded(){
}
}
Inside my code, u can see there is innerView of type UIView
as a private property. There is the frame for that view I want to set everytime iOS updates my CustomView's frame if someone or I add NSLayoutConstraint
in my CustomView instance.
When iOS
updates the UIViewController
's subviews by means of NSLayoutConstraint
, which one is called, layoutIfNeeded()
or layoutSubviews()
?
Swift or Objective-C , it doesnt matter.