addTarget传值,addTarget传多个值,最简单的方法

本文介绍了一种在iOS开发中简化UIButton传参的方法。通过创建UIButton的子类SelfButton,并利用字典和数组来传递多个参数,使得按钮点击事件能够携带更丰富的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做项目的时候遇到一个问题就是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,运行,点击两个按钮就能看见效果啦

 

转载于:https://www.cnblogs.com/huangzhenwei/p/6016462.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值