2011-10-04 164 views
8

我已經創建了一個UIButton的子類來給它一個白色的2px沒有半徑邊框,現在我試圖根據按鈕狀態「全局」設置它的字體,字體顏色和背景顏色。UIButton子類 - 設置屬性?

字體未設置。顏色或背景顏色也不一樣。這是怎麼回事?這是我的代碼。我希望你能幫到:)

- (id)initWithFrame:(CGRect)frame { 
self = [super initWithFrame:frame]; 
if (self) { 

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]]; 
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; 
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    if(self.state == UIControlStateHighlighted) { 
     [self setBackgroundColor:[UIColor whiteColor]]; 
    } 
    else { 
     [self setBackgroundColor:[UIColor blackColor]]; 
    } 
} 
return self; 
} 





// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 

      [self.layer setMasksToBounds:YES]; 
[self.layer setBorderWidth:2.0]; 
[self.layer setCornerRadius:0.0]; 
[self.layer setBorderColor:[[UIColor colorWithWhite:1.0 alpha:1.0] CGColor]]; 
} 

我不認爲我做錯了什麼。我有這個類,並在IB鏈接按鈕,並設置類的類型......

感謝,

奔奔

回答

17

如果您已經創建了IB的自定義子類按鈕,initWithFrame:不會調用。您需要覆蓋initWithCoder:,或者,最好創建一個單獨的設置方法,該方法從initWithFrame:initWithCoder:中均被調用。

對於第一種情況:

- (id)initWithCoder:(NSCoder*)coder { 
self = [super initWithCoder:coder]; 
if (self) { 

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]]; 
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; 
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    if(self.state == UIControlStateHighlighted) { 
     [self setBackgroundColor:[UIColor whiteColor]]; 
    } 
    else { 
     [self setBackgroundColor:[UIColor blackColor]]; 
    } 
} 
return self; 
} 
+0

我到底該如何去做呢?我從來沒有去過大學,這是所有自學成爲迄今.. – topLayoutGuide

+0

你和我都:)。查看更新回答 – jrturton

0

UIButton的是一類集羣。你真的不應該繼承,因爲它所代表的類是私有的。

+1

它在技術上並不是一個類集羣,但您的確有一個好的觀點,它在子類化時會變得複雜(請參閱http://stackoverflow.com/questions/816024/how-to-override-drawrect-in-uibutton-子類)和UIControl的子類化可能是更好的選擇。 – jrturton

1

這裏是我如何做到這一點(沒有IB):

+ (instancetype)customButtonWithCustomArgument:(id)customValue { 
    XYZCustomButtom *customButton = [super buttonWithType:UIButtonTypeSystem]; 
    customButton.customProperty = customValue; 
    [customButton customFunctionality]; 
    return customButton; 
} 

作品也與其他類型,UIButtonTypeSystem僅僅是一個例子。