target-action是iOS中UIControl控件下使用的最常见的消息传递方式,target-action在中文中就是目标-动作,也算是一种简单的设计模式.
target-action 传值
tag
target-action 模式传值一般通过tag来实现。
tag是一个无符号整形,所有的UIKit控件都有这个属性,在设定控件时可以加上tag值,在响应事件action中可以获取到sender,通过获取sender的tag来达到传值的功能。
category 添加传值方法
tag只能传递一个整形数字,这有很大的局限性,平时我们开发时可能还需要传递一些复杂的数据,这个时候tag就显得很局促了。
所以我们可以通过给父类添加category的方式,添加一个info的字典,用来传递消息。
添加category

使用runtime实现info的getter方法和setter方法:

在使用时设置info的值:
UIButton*targetBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
targetBtn.frame =CGRectMake(0, HEIGHT/2-50, WIDTH,100);
targetBtn.tag =100; [targetBtn setTitle:@"点我"forState:UIControlStateNormal];
[targetBtn setTitleColor:[UIColorblueColor] forState:UIControlStateNormal];
[targetBtn addTarget:selfaction:@selector(targetBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[targetBtn setInfo:@{@"id":@"12138",@"name":@"target-action"}];
[self.view addSubview:targetBtn];
在action中获取info中的值:
- (void)targetBtnClicked:(UIButton*)sender
{
NSLog(@"我被点击了");
NSLog(@"tag:%ld",(long)sender.tag);
NSDictionary*info = sender.info;
NSLog(@"%@",info);
}
这里我们是对NSObject进行的一个拓展,写完这个拓展之后,只要在继承了NSObject的类的控件使用时,引入头文件:
#import"NSObject+MPTargetActionPassing.h"
网友评论