2017-05-08 83 views
1

我創建一個自定義的UIButton與此代碼:iOS的設計性按鈕的背景顏色不工作

@implementation HGButton 

- (instancetype)initWithFrame:(CGRect)frame 
{ 
    if (self = [super initWithFrame:frame]) { 
     [self initVariables]; 
     [self customInit]; 
    } 

    return self; 
} 

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    self = [super initWithCoder:aDecoder]; 
    if (self) { 
     [self initVariables]; 
     [self customInit]; 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect 
{ 
    [self customInit]; 
} 

- (void)setNeedsLayout 
{ 
    [super setNeedsLayout]; 
    [self setNeedsDisplay]; 
} 

- (void)prepareForInterfaceBuilder 
{ 
    [self customInit]; 
} 

-(void) initVariables 
{ 
    self.fillColor   = [UIColor lightGrayColor]; 
    self.borderWidth  = 2; 
    self.cornerRadious  = 10; 
} 

- (void)customInit 
{ 
    [self setBackgroundColor:self.fillColor]; 

    self.layer.cornerRadius = self.cornerRadious; 
    self.layer.borderWidth = self.borderWidth; 

    if (self.cornerRadious > 0) { 
     self.layer.masksToBounds = YES; 
    } 
} 

這是一個非常簡單的代碼。當我的按鈕添加到故事板中的視圖時,它看起來很完美。 但是,當我玩這個應用程序時,按鈕背景顏色總是淺灰色。 當我按下按鈕時,它的背景顏色變爲故事板中選定的顏色。

這是爲什麼?錯誤在哪裏?

回答

1

因爲當您通過故事板更改self.fillcolor時,您沒有更新背景顏色。

假設你有這樣的

@property (nonatomic, copy) IBInspectable UIColor *fillcolor; 

添加以下代碼在類

- (void)setFillColor:(UIColor *)fillColor { 
    if (fillColor != _fillColor) { 
     _fillColor = fillColor; 
     [self customInit]; 
    } 
} 

希望這有助於。

乾杯。

+0

謝謝,現在的作品;) –

0

你應該寫一個'set method'來監視fillColor。

- (void)setFillColor:(UIColor *)fillColor 
{ 
    _fillColor = fillColor; 
    self.backgroundColor = fillColor; 

} 
0

在你的類添加此

- (void)setFillColor:(UIColor *)fillColor { 
    self.backgroundColor = fillColor; 
}