2011-10-04 182 views
8

我已经创建了一个UIButton的子类来给它一个白色的2px没有半径边框,现在我试图根据按钮状态“全局”设置它的字体,字体颜色和背景颜色。UIButton子类 - 设置属性?

字体未设置。颜色或背景颜色也不一样。这是怎么回事?这是我的代码。我希望你能帮到:)

- (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]]; 
} 

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

感谢,

奔奔

回答

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; 
} 
+0

我到底该如何去做呢?我从来没有去过大学,这是所有自学成为迄今.. – topLayoutGuide

+0

你和我都:)。查看更新回答 – jrturton

0

UIButton的是一类集群。你真的不应该继承,因为它所代表的类是私有的。

+1

它在技术上并不是一个类集群,但您的确有一个好的观点,它在子类化时会变得复杂(请参阅http://stackoverflow.com/questions/816024/how-to-override-drawrect-in-uibutton-子类)和UIControl的子类化可能是更好的选择。 – jrturton

1

这里是我如何做到这一点(没有IB):

+ (instancetype)customButtonWithCustomArgument:(id)customValue { 
    XYZCustomButtom *customButton = [super buttonWithType:UIButtonTypeSystem]; 
    customButton.customProperty = customValue; 
    [customButton customFunctionality]; 
    return customButton; 
} 

作品也与其他类型,UIButtonTypeSystem仅仅是一个例子。