IOS分类(Category)的使用

新建一个分类是选择下图红色框内的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");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值