假设我创建了一个UIView
的子类来创建自定义UI组件,我在自定义视图中有另一个视图。
这是代码
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(){
}
}
在我的代码中,你可以看到类型UIView
的innerView作为私有属性。如果有人或我在我的CustomView实例中添加NSLayoutConstraint
,每当iOS更新我的CustomView框架时,我想设置该视图的框架。
当iOS
通过UIViewController
更新NSLayoutConstraint
子视图时,会调用哪一个,layoutIfNeeded()
或layoutSubviews()
?
Swift或Objective-C,没关系。