我用这段代码创建了一个自定义 UIButton:
@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;
}
}
这是一个非常简单的代码。将我的按钮添加到 Storyboard 中的 View 时,它看起来很完美。 但是当我播放应用程序时,按钮背景颜色始终为浅灰色。 当我按下按钮时,它的背景颜色会更改为 Storyboard 中选择的颜色。
这是为什么?哪里出错了?
最佳答案
因为当 self.fillcolor
已通过 Storyboard更改时,您没有更新背景颜色。
假设你有这个
@property (nonatomic, copy) IBInspectable UIColor *fillcolor;
在你的类中添加以下代码
- (void)setFillColor:(UIColor *)fillColor {
if (fillColor != _fillColor) {
_fillColor = fillColor;
[self customInit];
}
}
希望这对您有所帮助。
干杯。
关于iOS 可设计按钮背景颜色不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844948/