步驟:佈局
#import <UIKit/UIKit.h>atom
@interface myView : UIViewspa
@property(nonatomic,strong)UIButton *btn;.net
@property(nonatomic,strong)UILabel *label;對象
@end繼承
問題:爲何不重寫init 方法呢?get
由於有可能別人會用你的myView,他可能建立對象的方式是it
myView *v = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 100, 100)]; 這樣的話 你寫在init方法中的子控件就不會被建立,運行後就不會顯示子控件了。而重寫initWithFrame的話,無論別人是init 仍是initWithFrame 都會調用到initWithFrame, 由於init方法內部是會調用initWithFrame方法的。class
代碼1:import
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.imageView = [[UIImageView alloc]init];
self.imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.width);
[self addSubview:self.imageView];
}
return self;
}
代碼2:僅僅將子控件放進去。
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.imageView = [[UIImageView alloc]init];
[self addSubview:self.imageView];
}
return self;
}
- (void)layoutSubviews {
// 必定要調用super的方法
[super layoutSubviews];
// 肯定子控件的frame(這裏獲得的self的frame/bounds纔是準確的)
CGFloat width = self.bounds.size.width;
self.imageView.frame = CGRectMake(0, 0, width/2, width);
}