如何重用属性

How to reuse properties

我的应用程序中有许多不同的按钮,但大多数按钮都分配了相同的属性:

login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[login setTitle:@"Login" forState:UIControlStateNormal];
[login.titleLabel setFont:[UIFont fontWithName:@"Avenir Next" size:18]];
[login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[login setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted];
[login setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled];

有什么方法可以创建 class 或已经分配了这些默认属性的按钮吗?所以我可以简单地做类似的事情:

CustomButtom *btn = [CustomButton alloc]init];

那么 btn 将分配上述所有属性?

谢谢。

是的。您可以子类化 UIButton。当您覆盖设置属性的 init 方法时,您可以获得具有相同属性的按钮。

另一种处理方法是,您可以创建一个私有方法,该方法将 return 具有相同属性的 UIButton。我认为创建 UIButton 的子类有点不必要。

您可以通过创建 CustomButton class

来实现

Xcode -> 新文件 -> Cocoa 触摸 Class -> Next -> 命名你的按钮-> Select Subclass of UIButton

CustomButton.h 文件

#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@end

CustomButton.m 文件

#import "CustomButton.h"

@implementation CustomButton


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
//login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[self setTitle:@"Login" forState:UIControlStateNormal];
[self.titleLabel setFont:[UIFont fontWithName:@"Avenir Next" size:18]];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled];
}

@end 

现在,叫你按钮

CustomButton *customButton = [[CustomButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[customButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchDown];
[YourView addSubview:customButton];

您有两个选择: