系統原生的 UIButton 在 addTarget:action:forControlEvents: 中只會把 button 本身傳回來,也就是說 action 方法固定只有一個參數。當我們需要在點擊時帶上「第幾列」、「哪筆資料」這類額外資訊,就得自己想辦法。以下整理六種常見做法,從最簡單到最靈活,並說明各自的適用情境。
如果場景單純,只需要一個整數索引,tag 是最省事的選擇:
[cell.deleteButton setTag:indexPath.row]; // 把 cell 的行號存成 tag
缺點很明顯:只能存一個整數,語意也不清楚,適合臨時或極簡單的情況。
Objective-C 的 runtime 提供了「幫任何物件掛上額外屬性」的能力,等於用 KVC 的思路把參數綁在 button 上:
UIButton *btn = /* create the button */
objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
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(sender, "firstObject");
id second = objc_getAssociatedObject(sender, "secondObject");
// ...
}
寫法簡短,但 key 建議用 static 位址而非字串字面值,取參時也記得用傳入的 sender,別誤用外層變數。
最直覺的做法:繼承一個子類,加一個 dictionary 屬性,想裝多少參數都可以,而且完全不用覆寫任何方法。
@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(@"params : %@", multiParamButton.multiParamDic);
}
若不想自訂子類,用 Category 加 property 並自行實作 getter/setter(內部走關聯物件)也完全可行。
這一類需求最常出現在 UITableViewCell 內部的按鈕上:cell 只知道自己的資料,真正的業務參數在 view controller 裡。既然視圖繼承樹上的任何一層都能取得,那麼沿著 superview 往上找到所屬的 view controller,就能間接把參數取出來。
#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 *controller = nil;
// 取得 button 所屬的視圖控制器;能拿到控制器,其他資料自然都能拿到
for (UIView *next = [button superview]; next; next = next.superview)
{
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[LBMultiParamButtonController class]])
{
controller = (LBMultiParamButtonController *)nextResponder;
break;
}
}
NSLog(@"param : %@", controller.paramDic);
}
@end
這招在自訂 cell 的按鈕上非常實用,缺點是依賴視圖階層結構,層級一改就可能失效。
performSelector:withObject:withObject: 最多帶兩個物件參數,搭配 delegate 就能把 cell 與 button 一起往上遞。
#pragma mark - SYAccountListCellDelegate @class SYAccountListCell; @protocol SYAccountListCellDelegate <NSObject> - (void)accountListCell:(SYAccountListCell *)cell didTapButton:(UIButton *)button; @end
自訂 cell 時把要傳的東西一起送出去:
@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
在控制器這端實作:
#pragma mark - SYAccountListCellDelegate
- (void)accountListCell:(SYAccountListCell *)cell didTapButton:(UIButton *)button
{
NSLog(@"Cell : %@ , Button : %@", cell, button);
}
寫法繞了一點,但資料流向清楚、耦合度低。要補充的是,「最多兩個參數」指的是直接傳入的物件個數;如果把參數打包成一個結構體或物件,實際能帶的資訊完全沒有上限。
用 Category 幫 UIButton 加上「綁定 block」的能力,點擊時直接執行,參數在 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
使用時把行為寫在 block 裡,參數直接取用:
[button handleControlEvent:UIControlEventTouchUpInside withBlock:^{
NSLog(@"params : %@", self.paramDic);
}];
只需要一個索引值:用 tag。
不想改 button 型別、參數數量固定:關聯物件或自訂子類。
cell 內的按鈕、需要呼叫控制器的業務方法:delegate 最合適,也最好測試。
點擊行為本身需要高度客製、且與所在控制器無關:block 方案最乾淨。
要注意的是,關聯物件與 Category 都是靠 runtime 实现的約定,key 請統一管理;另外在 block 中若強引用 self,記得搭配 weak self 避免循環參考。