UIButton子类 - 设置属性?

top*_*ide 8 xcode objective-c uibutton ios4 ios

我创建了一个UIButton子类,给它一个白色的2px No Radii边框,现在我试图"全局"设置它的字体,字体颜色和背景颜色,具体取决于按钮状态.

字体未设置.颜色或背景颜色也没有.这是怎么回事?这是我的代码.我希望你能帮忙:)

- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if(self.state == UIControlStateHighlighted) {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
    else {
        [self setBackgroundColor:[UIColor blackColor]];
    }
}
return self;
}





// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {

             [self.layer setMasksToBounds:YES];
[self.layer setBorderWidth:2.0];
[self.layer setCornerRadius:0.0];
[self.layer setBorderColor:[[UIColor colorWithWhite:1.0 alpha:1.0] CGColor]];
}
Run Code Online (Sandbox Code Playgroud)

我不认为我做错了什么.我有这个类,并在IB中链接了按钮,并设置类类型...

谢谢,

奔奔

jrt*_*ton 17

如果您在IB中创建了自定义子类按钮,initWithFrame:则不会被调用.您需要覆盖initWithCoder:,或者最好创建一个单独的设置方法,该方法同时从initWithFrame:和调用initWithCoder:.

对于第一种情况:

- (id)initWithCoder:(NSCoder*)coder {
self = [super initWithCoder:coder];
if (self) {

    [[self titleLabel] setFont:[UIFont fontWithName:@"ZegoeUI" size:18]];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if(self.state == UIControlStateHighlighted) {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
    else {
        [self setBackgroundColor:[UIColor blackColor]];
    }
}
return self;
}
Run Code Online (Sandbox Code Playgroud)