【问题标题】:iOS Designable Button Background color don't workiOS 可设计按钮背景颜色不起作用
【发布时间】:2023-03-03 09:16:23
【问题描述】:

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

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

为什么会这样?哪里出错了?

【问题讨论】:

    标签: ios iphone xcode storyboard ibdesignable


    【解决方案1】:

    因为当 self.fillcolor 通过故事板更改时,您没有更新背景颜色。

    假设你有这个

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

    在你的类中添加以下代码

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

    希望这会有所帮助。

    干杯。

    【讨论】:

      【解决方案2】:

      您应该编写一个“设置方法”来监控填充颜色。

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

      【讨论】:

        【解决方案3】:

        在你的课堂上添加这个

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

        【讨论】:

          猜你喜欢
          • 2016-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-19
          • 1970-01-01
          • 2021-04-14
          相关资源
          最近更新 更多