Button多参数点击

iOS 原生的 UIButton 点击事件是不允许带多参数的,唯一的一个参数就是默认UIButton本身
那么我们该怎么实现传递多个参数的点击事件呢?

1.如果业务场景非常简单,要求传单参数并且是整数类型,可以用tag

[cell.deleteButton setTag:indexPath.row];  //例如,将cell的行数设置成tag  

2.利用ObjC关联,runtime之所以被称为iOS 的动态特性是有道理的,当然关联甚至可以帮助NSArray等其他对象实现“多参数传递”
实现起来也非常简便:

UIButton *btn = // create the button  
objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);   //实际上就是KVC  
objc_setAssociatedObject(btn, "secondObject", otherObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);  
  
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];  
  
- (void)click:(UIButton *)sender  
{  
    id first = objc_getAssociatedObject(btn, "firstObject");        //取参  
    id second = objc_setAssociatedObject(btn, "secondObject");  
    // etc.  
}  

3.利用自定义,添加一个多参数的字典属性变量即可(为什么要字典?可以装多多的)
自定义Button子类,甚至都不用重写啥的:

@interface MultiParamButton : UIButton  
  
@property (nonatomic, strong) NSDictionary* multiParamDic;  
  
@end  

传参:

NSDictionary* paramDic = @{@"one":@"one", @"two":@2, @"third":@(3)};  
  
MultiParamButton* multiParamButton = [[MultiParamButton alloc] init];  
[multiParamButton setFrame:CGRectMake(0, 0, 50, 50)];  
multiParamButton.center = self.view.center;  
[multiParamButton setBackgroundColor:[UIColor grayColor]];  
[multiParamButton addTarget:self action:@selector(multiParamButtonClicked:) forControlEvents:UIControlEventTouchUpInside];  
[self.view addSubview:multiParamButton];  
  
multiParamButton.multiParamDic = paramDic;  

点击:

- (void)multiParamButtonClicked:(UIButton* )button  
{  
    MultiParamButton* multiParamButton = (MultiParamButton* )button;  
      
    NSLog(@"Vvvverify : %@", multiParamButton.multiParamDic);  
}  

爽爽的:


当然,如果用扩展,然后添加property后重写GetSet也是一样一样的

4.完全不在Button上入手,针对业务来,最常见的就是在TableViewCell上面的Button,这种存在(视图)继承树之间的传递,这里举个简单的例子
Button获取所属父视图的所属视图控制器的参数,间接传参

#import "LBMultiParamButtonController.h"  
#import "MultiParamButton.h"  
  
@interface LBMultiParamButtonController ()  
@property (nonatomic, strong) NSDictionary* paramDic;  
@end  
  
@implementation LBMultiParamButtonController  
  
- (id)init  
{  
    self = [super init];  
  
    if (self)  
    {  
        _paramDic = @{@"one":@"one", @"two":@2, @"third":@(3)};  
    }  
      
    return self;  
}  
  
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
      
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];  
    [button setFrame:CGRectMake(0, 0, 50, 50)];  
    [button setCenter:self.view.center];  
    [button setBackgroundColor:[UIColor grayColor]];  
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];  
    [self.view addSubview:button];  
}  
  
- (void)buttonClicked:(UIButton* )button  
{  
      
    LBMultiParamButtonController* multiParamButtonController = nil;        
    //获取button所属的视图控制器,如果视图控制器都能获取,还有什么不能获取呢?  
    for(UIView* next = [button superview]; next; next = next.superview)  
    {  
        UIResponder *nextResponder = [next nextResponder];  
        if ([nextResponder isKindOfClass:[LBMultiParamButtonController class]])  
        {  
            multiParamButtonController = (LBMultiParamButtonController* )nextResponder;  
            break;  
        }  
    }  
      
    NSLog(@"param : %@", multiParamButtonController.paramDic);  
}  
  
@end  

这种非常多的用在UITableViewCell上自定义的按钮的参数的情况!

5.利用Delegate和performSelector:withObject:withObject 方法可以传递最多两个参数:
定义protocol:

#pragma mark - SYAccountListCellDelegate.  
  
@class SYAccountListCell;  
  
@protocol  SYAccountListCellDelegate <NSObject>  
  
- (void)accountListCell:(SYAccountListCell* )cell didTapButton:(UIButton* )button;  
  
@end  

自定义Cell的时候将你想传的东西传进入,这里用cell和button做例子:

@implementation SYAccountListCell  
  
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier  
{  
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];  
      
    if (self)  
    {  
          
        self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];  
        [self.deleteButton setFrame:CGRectMake(225,  
                                               5,  
                                               40,  
                                               40)];  
        [self.deleteButton setBackgroundColor:[UIColor redColor]];  
        [self.deleteButton addTarget:self action:@selector(deleteButtonClicked:) forControlEvents:UIControlEventTouchUpInside];  
        [self.contentView addSubview:self.deleteButton];  
    }  
      
    return self;  
}  
  
- (void)deleteButtonClicked:(UIButton* )button  
{  
    if ([self.delegate respondsToSelector:@selector(accountListCell:didTapButton:)])  
    {  
        [self.delegate performSelector:@selector(accountListCell:didTapButton:) withObject:self withObject:button];  
    }  
}  
  
@end  

Delegate实现:

#pragma mark - SYAccountListCellDelegate.  
  
- (void)accountListCell:(SYAccountListCell *)cell didTapButton:(UIButton *)button  
{  
    NSLog(@"Cell : %@ , Button : %@", cell, button);  
}  

虽然有点曲折,但是传参效果非常到位
这里补充一下,这里的最多两个参数是直面的参数个数,如果将参数设置位结构体,那么就皆大欢喜啦,想怎么传就怎么传!

6.利用Block 和 关联 , 直接可以当前点击并且操作参数 - 强!

#import <UIKit/UIKit.h>  
  
typedef void (^ActionBlock)();  
  
@interface UIButton (Utility)  
  
@property (readonly) NSMutableDictionary *event;  
  
- (void) handleControlEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action;  
  
@end  

实现文件:

#import <objc/runtime.h>  
#import "UIButton+Utility.h"  
  
@implementation UIButton (Utility)  
  
static char overviewKey;  
  
@dynamic event;  
  
- (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block  
{  
    objc_setAssociatedObject(self, &overviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);  
      
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];  
}  
  
  
- (void)callActionBlock:(id)sender  
{  
    ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &overviewKey);  
      
    if (block)  
    {  
        block();  
    }  
}  
  
@end  

操作:

[button handleControlEvent:UIControlEventTouchUpInside withBlock:^{  
    NSLog(@"ssss : %@", self.paramDic);  
}];  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,063评论 6 510
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,805评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,403评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,110评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,130评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,877评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,533评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,429评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,947评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,078评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,204评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,894评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,546评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,086评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,195评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,519评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,198评论 2 357

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,216评论 25 707
  • 随着离去的脚步, 雪花也为你飞舞。 前途的迷路 有谁为你解忧 任雪花潇潇洒洒 也无意阻挡韩流 前途的迷路 只有自己...
    纯真的云卷云舒_6阅读 119评论 0 2
  • 我们之间是没法交流的,而我很清楚问题不在我身上,或许我确实缺乏一些耐心。可我无法理解她不能用一点点的时间来听我把事...
    灯塔高处阅读 152评论 0 0
  • 这本书的作者被《快公司》誉为“商业领域最具创意的一百人”和“推特上最具创意的十位博主”之一。她的绝招是涂鸦,通过“...
    朱桃子阅读 277评论 2 1
  • 类主构造器 主构造器的定义与类的定义交织在一直,将构造器参数直接放在类名称之后,如下代码: 主构造器还可以使用默认...
    LuciferTM阅读 274评论 0 0