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

标签 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;
    }
}

这是一个非常简单的代码。将我的按钮添加到 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/

相关文章:

android - 用于 react native 应用程序图标角标(Badge)的库

ios - 如何从应用程序的文档目录中检索音乐的艺术家信息

ios - 从 NSData 解码 MP3 文件

ios - 无法将试用应用程序上传到 iPhone 进行测试

ios - 从另一个 ViewController 访问变量

c++ - 缺少着色器 C 兼容性是否重要?

iphone - 在我的 App 中的 App Store 中打开我的应用程序列表

iOS 企业配置文件到期

ios - 使用设备上的仪器进行自动化测试

ios - 推送到另一个 ViewController