新建一个分类是选择下图红色框内的file类型
在这里我写了一个简单的分类,是对UIButton增加两个自己常用的方法
UIButton+Test.h
#import <UIKit/UIKit.h>
@interface UIButton (Test)
@property(nonatomic,retain) NSString *secondTitle;//增加属性
- (void)setTiTleForNormalState:(NSString *)title;
- (void)addTarget:(id)target touchUpInsideAction:(SEL)action;
@end
UIButton+Test.m
#import "UIButton+Test.h"
#import <objc/runtime.h>
@implementation UIButton (Test)
//在分类的.m文件中不能使用@synthesize关键字,所以用以下方法实现
static void *key = (void *)@"key";
- (NSString *)secondTitle
{
return objc_getAssociatedObject(self, key);
}
- (void)setSecondTitle:(NSString *)secondTitle
{
objc_setAssociatedObject(self, key, secondTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
/**
* 给按钮增加一个状态为UIControlStateNormal的标题
*
* @param title 标题
*/
- (void)setTiTleForNormalState:(NSString *)title
{
[self setTitle:title forState:UIControlStateNormal];
}
/**
* 给按钮增加一个事件为UIControlEventTouchUpInside的响应方法
*
* @param target 接受者
* @param action 响应方法
*/
- (void)addTarget:(id)target touchUpInsideAction:(SEL)action
{
[self addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}
@end
使用(需要在使用的地方引入头文件 #import "UIButton+Test.h" ):
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(0, 100, 320, 50)];
[button setBackgroundColor:[UIColor orangeColor]];
[button setTiTleForNormalState:@"UIButton+Test"];
[button addTarget:self touchUpInsideAction:@selector(touchUpInsideAct)];
[self.view addSubview:button];
button.secondTitle = @"button.secondTitle";
NSLog(@"button.secondTitle value:%@",button.secondTitle);
}
- (void)touchUpInsideAct
{
NSLog(@"UIButton+Test touchUpInsideAct");
}