2016-11-20 172 views
0

我在drawRect中將UIButton添加到我的UIView筆尖中。以編程方式將子視圖添加到NIB的方法

-(void)drawRect:(CGRect)rect { 
    self.button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)]; 
    [self.button setImage:[UIImage imageNamed:@"buttonImage.png"] forState:UIControlStateNormal]; 
    [self.button setTintColor:[UIColor whiteColor]]; 
    [self addSubview:self.button]; 
} 

閱讀本post後,它說,每當視圖幀被修改drawRect被調用。我應該添加哪些方法來定製用戶界面元素,還是應該創建自己的方法並調用它。

+1

覆蓋'initWithFrame'和'initWithCoder'。調用一個方法在那裏添加你的按鈕。 – Paulw11

回答

1

通常我不喜歡這樣

-(instancetype)initWithCoder:(NSCoder *)aDecoder{ 

    self = [super initWithCoder:aDecoder]; 
    if(self) 
    { 
     [self load] ; 
    } 
    return self ; 
} 

-(instancetype)initWithFrame:(CGRect)frame{ 
    self = [super initWithFrame:frame] ; 
    if(self) 
    { 
     [self load] ; 
    } 
    return self ; 
} 
-(void)load{ 
    //add your subviews here . 
} 
相關問題