每次用 UIButton 都要另外寫一個 IBAction 方法,按鈕一多,檔案裡就塞滿了單行方法。今天沒事,就用 block 把按鈕與警告框的操作封裝起來,之後寫起來省事,程式碼量也少很多。
#import <UIKit/UIKit.h>
typedef void (^ActionBlock)();
typedef void (^Block_SureEvent)();
@interface UIButton (Block) <UIAlertViewDelegate>
- (void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent;
- (void)AlertViewTitle:(NSString *)aTitle
message:(NSString *)aMsg
cancleButtonTitle:(NSString *)aButtonTitle
sureButtonTitle:(NSString *)aSureButton
sureBlockEvent:(Block_SureEvent)aSureEvent;
@end
#import "UIButton+Block.h"
#import <objc/runtime.h>
static char *overViewKey;
@implementation UIButton (Block)
- (void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent
{
objc_setAssociatedObject(self, &overViewKey, buttonClickEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(buttonClick) forControlEvents:aEvent];
}
- (void)buttonClick
{
ActionBlock blockClick = objc_getAssociatedObject(self, &overViewKey);
if (blockClick != nil) {
blockClick();
}
}
@end
這裡的技巧是關聯物件(associated object)。category 無法直接新增實例變數,但透過 objc_setAssociatedObject 可以把 block 掛在按鈕物件上,點擊時再由統一的 buttonClick 取出並執行。
使用關聯物件必須引入 objc/runtime.h。objc_setAssociatedObject 的四個參數分別是:來源物件、key(必須是 static char 型別)、關聯的物件、關聯策略(與宣告屬性的修飾子類似,這裡用 COPY 因為 block 需要被複製);objc_getAssociatedObject 則只要來源物件與 key。
static char *alertKey;
- (void)AlertViewTitle:(NSString *)aTitle
message:(NSString *)aMsg
cancleButtonTitle:(NSString *)aButtonTitle
sureButtonTitle:(NSString *)aSureButton
sureBlockEvent:(Block_SureEvent)aSureEvent
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle
message:aMsg
delegate:self
cancelButtonTitle:aButtonTitle
otherButtonTitles:aSureButton, nil];
objc_setAssociatedObject(self, &alertKey, aSureEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
Block_SureEvent blockSure = objc_getAssociatedObject(self, &alertKey);
if (blockSure != nil) {
blockSure();
} else {
NSLog(@"error");
}
}
}
[self.publishButton handleClickEvent:UIControlEventTouchUpInside withClickBlick:^{
NSLog(@"按下發布");
}];
[self AlertViewTitle:@"確認刪除" message:@"刪除後無法復原"
cancleButtonTitle:@"取消" sureButtonTitle:@"確定"
sureBlockEvent:^{
NSLog(@"使用者按下確定");
}];
&key 傳入,且各個 category 之間不要共用同一個 key。UIAlertController 的 block 型 API。