純代碼自定義View

步驟:佈局

1.繼承UIView 建立一個myView

#import <UIKit/UIKit.h>atom

@interface myView : UIViewspa

@property(nonatomic,strong)UIButton *btn;.net

@property(nonatomic,strong)UILabel *label;對象

@end繼承

 

2.重寫initWithFrame 方法。

問題:爲何不重寫init 方法呢?get

由於有可能別人會用你的myView,他可能建立對象的方式是it

 myView *v = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 100, 100)]; 這樣的話 你寫在init方法中的子控件就不會被建立,運行後就不會顯示子控件了。而重寫initWithFrame的話,無論別人是init 仍是initWithFrame 都會調用到initWithFrame, 由於init方法內部是會調用initWithFrame方法的。class

 

3.從新initWithFrame 方法時。

若是子控件imageView的寬和高直接用self.frame.size.width,這種形式的話(以下面代碼1),這個時候self.frame 可能沒值,由於若是外部調用了MyView的init方法,也會執行到這裏,這個時候frame尚未賦值,會致使沒法顯示子控件。

若是你是寫死的frame,好比self.imageView.frame = CGRectMake(0, 0, 100, 100); 這樣的就不會有問題。(以下面代碼2)

總結:咱們最好不要將子控件的frame設置寫在initWithFrame中。咱們要作的僅僅是把子控件放進去就好了

 

代碼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;

}

 

3.在layoutSubViews方法裏面佈局子控件

- (void)layoutSubviews {

    // 必定要調用super的方法

    [super layoutSubviews];

    // 肯定子控件的frame(這裏獲得的self的frame/bounds纔是準確的)

    CGFloat width = self.bounds.size.width;

    self.imageView.frame = CGRectMake(0, 0, width/2, width);

}

相關文章
相關標籤/搜索