2013-04-12 70 views
1

好吧,我以爲我有一個好主意。一個帶有大括號的UIButton自動應用於背景圖像。UIButton子類自動應用

@implementation JLTCapInsetButton 

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state 
{ 
    CGFloat leftRight = (image.size.width - 1)/2; 
    CGFloat topBottom = (image.size.height - 1)/2; 
    UIEdgeInsets insets = UIEdgeInsetsMake(topBottom, leftRight, topBottom, leftRight); 
    UIImage *capInsetImage = [image resizableImageWithCapInsets:insets]; 

    [super setBackgroundImage:capInsetImage forState:state]; 
} 

@end 

這不起作用,因爲IB不使用-setBackgroundImage:forState:。我的解決方法是使用-awakeFromNib

- (void)awakeFromNib 
{ 
    [self JLT_fixBackgroundImageForState:UIControlStateNormal]; 
    [self JLT_fixBackgroundImageForState:UIControlStateHighlighted]; 
    [self JLT_fixBackgroundImageForState:UIControlStateDisabled]; 
    [self JLT_fixBackgroundImageForState:UIControlStateSelected]; 
    [self JLT_fixBackgroundImageForState:UIControlStateSelected | UIControlStateHighlighted]; 
    [self JLT_fixBackgroundImageForState:UIControlStateSelected | UIControlStateDisabled]; 
} 

- (void)JLT_fixBackgroundImageForState:(UIControlState)state 
{ 
    UIImage *backgroundImage = [self backgroundImageForState:state]; 

    if (backgroundImage) 
     [self setBackgroundImage:backgroundImage forState:state]; 
} 

這不起作用,因爲[self backgroundImageForState:state]總是返回如果圖像是爲UIControlStateNormal設置的值。

解碼時是否有一種乾淨的方式來掛鉤背景圖像的設置?是否有一種乾淨的方式來檢測一個狀態是否具有背景圖像,而不僅僅是來自基態的隱含圖像?

回答

1

如何在修復之前保持對已應用於UIControlStateNormal的圖像的引用?對於隨後的控制狀態,只需檢查圖像是否應用修補程序之前是否相同,如果是,則跳過修復該狀態的圖像...

+0

我終於回到了這一點。我測試了你的建議,它工作。好極了! –

+0

酷,很高興它幫助!謝謝你回到我身旁 :) – Toastor