addTarget传值,addTarget传多个值,最简单的方法
做项目的时候遇到一个问题就是addTarget需要传递多个值,但是问了很多人都不会,自己百度了下,发现很麻烦也很繁琐,这里介绍一种最简单的方法。
使用tag传值这个就不啰嗦了,相信学过iOS的都会,介绍的是重写Button父类的方法,非常简单,拿过去都能直接使用。
1首先创建类,继承自UIButton,类名随便写,我这里使用SelfButton(也可使用类扩展)
#import <UIKit/UIKit.h> @interface SelfButton : UIButton //字典传值,,这里尽量使用可变的,赋值之后还可以对数据进行操作 @property (nonatomic, strong) NSMutableDictionary* multiParamDic; //数组传值 @property (nonatomic, strong) NSMutableArray* multiParamArr; @end
.m文件里面什么也不用写
2在viewDidLoad里面加入以下代码
//11111字典方法 NSMutableDictionary* selfDic =[[NSMutableDictionary alloc]initWithDictionary: @{@"one":@"one", @"two":@2, @"third":@(3)}]; // 赋值后还可以修改值 [selfDic setValue:@"修改后的one" forKey:@"one"]; // 创建按钮 SelfButton* sButton = [[SelfButton alloc] init]; [sButton setFrame:CGRectMake(0, 50, 50, 50)]; [sButton setBackgroundColor:[UIColor grayColor]]; [sButton addTarget:self action:@selector(dicClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:sButton]; // 把字典赋值为自定义按钮的字典对象 sButton.multiParamDic = selfDic; //2222 数组方法 NSMutableArray* selfArr=[[NSMutableArray alloc]initWithArray:@[@"1",@"2"]]; SelfButton* mButton1 = [[SelfButton alloc] init]; [mButton1 setFrame:CGRectMake(0, 100, 50, 50)]; [mButton1 setBackgroundColor:[UIColor redColor]]; [mButton1 addTarget:self action:@selector(arrClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:mButton1]; mButton1.multiParamArr=selfArr; // 修改值 selfArr[0]=@"xiugaide1";
3 把点击事件触发的事件沾到项目里面
- (void)dicClicked:(UIButton* )button { SelfButton* multiParamButton = (SelfButton* )button; NSLog(@"字典的方式 : %@", multiParamButton.multiParamDic); } - (void)arrClicked:(UIButton* )button { SelfButton* multiParamButton = (SelfButton* )button; NSLog(@"数组的方式 : %@", multiParamButton.multiParamArr); }
4,运行,点击两个按钮就能看见效果啦