在这里我以UIButton为例子给大家展示一种实现方法,主要依靠runtime实现。废话不说上码...
1.扩展一般属性NSString
@interface UIButton (CJButtonType)
@property (nonatomic, strong) NSString *typeString;
@end
///////////////////////////////////////////////
#import "UIButton+CJButtonType.h"
#import <objc/runtime.h>
@implementation UIButton (CJButtonType)
- (NSString *)typeString {
return objc_getAssociatedObject(self, @selector(typeString));
}
- (void)setTypeString:(NSString *)typeString {
objc_setAssociatedObject(self, @selector(typeString), typeString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
2.扩展枚举类型
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, BuyHouseCalculatorType) {
BuyHouseCalculatorType_PublicReserveFundLoan = 0,
BuyHouseCalculatorType_BusinessLoan,
BuyHouseCalculatorType_GroupLoan
};
@interface UIButton (CJButtonType)
@property (nonatomic, assign) BuyHouseCalculatorType buyHouseCalculatorType;
@end
#import "UIButton+CJButtonType.h"
#import <objc/runtime.h>
// 定义全局静态字符作为关联的Key值
const char *buyHouseCalculatorTypeKey = "buyHouseCalculatorTypeKey";
@implementation UIButton (CJButtonType)
- (void)setBuyHouseCalculatorType:(BuyHouseCalculatorType)buyHouseCalculatorType {
objc_setAssociatedObject(self, buyHouseCalculatorTypeKey, @(buyHouseCalculatorType), OBJC_ASSOCIATION_ASSIGN);
}
- (BuyHouseCalculatorType)buyHouseCalculatorType {
return [objc_getAssociatedObject(self, buyHouseCalculatorTypeKey) integerValue];
}
@end
3.扩展方法
//// .h
+ (UIButton *)button;
+ (UIButton *)buttonWithTitle:(NSString *)title titleColor:(UIColor *)color;
//// .m
+ (UIButton *)button {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
[button setClipsToBounds:YES];
[button setExclusiveTouch:YES];
return button;
}
+ (UIButton *)buttonWithTitle:(NSString *)title titleColor:(UIColor *)color {
UIButton *button = [UIButton button];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:color forState:UIControlStateNormal];
return button;
}
以上是鄙人的小小见解,喜欢的朋友可以互粉一起学习。。。。。