UIButton子类 - 如何设置属性?

9
我创建了一个UIButton的子类,给它添加了一个白色的2像素无边框,并且现在我正在尝试“全局”设置它的字体、字体颜色和背景颜色,具体取决于按钮的状态。
然而,字体没有被设置。颜色和背景颜色也都没有被设置。出了什么问题?以下是我的代码。希望你能帮忙 :)
- (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中链接了按钮,并设置了类类型。

3个回答

18
如果您在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;
}

我应该怎样做呢?我从未上过大学,到目前为止都是自学的。 - topLayoutGuide

1
这是我如何做到的(不使用IB):

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

这也适用于其他类型,UIButtonTypeSystem只是一个例子。


0

UIButton是一个类簇。你真的不应该去子类化它,因为它所代表的类是私有的。


1
虽然它在技术上不是一个类簇,但你说得很有道理。当子类化时可能会变得复杂(请参见https://dev59.com/WXRA5IYBdhLWcg3wzhbZ),因此子类化UIControl可能是更好的选择。 - jrturton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接