iOS可设计按钮背景颜色不起作用

时间:2017-05-08 10:10:03

标签: ios iphone xcode storyboard ibdesignable

我使用以下代码创建了一个自定义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;
    }
}

这是一个非常简单的代码。将我的按钮添加到故事板中的视图时,它看起来很完美。 但是,当我播放应用程序时,按钮背景颜色始终为浅灰色。 当我按下按钮时,它的背景颜色变为故事板中选择的颜色。

为什么这样?错误在哪里?

3 个答案:

答案 0 :(得分:1)

因为在通过情节提要更改self.fillcolor时您没有更新背景颜色。

假设你有这个

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

在班级中添加以下代码

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

希望这有帮助。

干杯。

答案 1 :(得分:0)

你应该写一个'set method'来监控fillColor。

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

 }

答案 2 :(得分:0)

在课堂上添加

workspace.xml
相关问题