UIButton的子类不工作

时间:2017-01-11 16:40:27

标签: ios objective-c uibutton subclass

我有一个应用程序,我需要多个标签才能在按钮上写文字,每天都会改变。为此,我正在设置UIButton的子类,但遇到了困难。我对子类的实现如下所示:

@implementation GlossyButton


- (id)initWithFrame:(CGRect)frame withBackgroundColor:(UIColor*)backgroundColor
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self makeButtonShiny:self withBackgroundColor:backgroundColor];
    }
    return self;
}

- (void)makeButtonShiny:(GlossyButton*)button withBackgroundColor:(UIColor*)backgroundColor
{
    // Get the button layer and give it rounded corners with a semi-transparant button
    UIColor *bobcatred = [UIColor whiteColor];

    CALayer* l = button.layer;

    CAGradientLayer *shineLayerl = [CAGradientLayer layer];
    shineLayerl.frame = l.bounds;
    shineLayerl.colors = [NSArray arrayWithObjects:
                          (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                          (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                          (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                          (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                          (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                          nil];
    shineLayerl.locations = [NSArray arrayWithObjects:
                             [NSNumber numberWithFloat:0.0f],
                             [NSNumber numberWithFloat:0.5f],
                             [NSNumber numberWithFloat:0.5f],
                             [NSNumber numberWithFloat:0.8f],
                             [NSNumber numberWithFloat:1.0f],
                             nil];

    [l setMasksToBounds:YES];
    [l setCornerRadius:11];
    [l setBorderWidth:2.0];
    [l setBorderColor: [bobcatred CGColor]];
    [l addSublayer:shineLayerl];
    // Add the layer to the button
    [button.layer addSublayer:shineLayerl];

    [button setBackgroundColor:[UIColor redColor]];
}

@end

我还没有添加标签,只是检查它是否会正确绘制所有内容。

然后我转到ViewController,然后为按钮添加一个IBOutlet属性。在故事板中,我将UIButton拖到视图上,将其属性更改为自定义,然后在课程中将其从UIButton更改为GlossyButton。然后我运行它,但它在应用程序中只有一个空白点,没有任何渐变,边框或任何东西。我做错了什么?

1 个答案:

答案 0 :(得分:3)

对于从故事板实例化的自定义UIButton子类,将不会调用initWithFrame。请改为initWithCoder