標籤:
通常都是這樣建立alert 再加一個代理
// 建立一個UIAlertView並顯示出來UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:aTitle message:msg delegate:self cancelButtonTitle:str otherButtonTitles:nil];[alertview show];-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ NSLogD(@"%ld", (long)buttonIndex);}
如果 像下邊的寫法 就顯得牛逼多了[[[UIAlertView alloc] initWithTitle:@"Delete This Item?" message:@"Are you sure you want to delete this really important thing?" cancelButtonItem:[RIButtonItem itemWithLabel:@"Yes" action:^{ // Handle "Cancel" }] otherButtonItems:[RIButtonItem itemWithLabel:@"Delete" action:^{ // Handle "Delete" }], nil] show];
這個 就是 閉包強大的地方了 不需要寫代理了哈哈 多方便 可讀性還強
得了懶癌 就去這個連結 下載直接用 不然 就往下看哦 高度自訂 https://github.com/jivadevoe/UIAlertView-Blocks
就是在 想要執行 這個 block方法的時候 實施方法 xxx.action();當然 要預判斷 是否存在這個方法 if(xxx.action) //這是個無參數的 閉包 如果要寫有參數 閉包 參見 閉包的寫法
//// HFLittleHelperButton.h// dailylife//// Created by HF on 15/12/5.////#import "HFBorderLineButton.h"@interface HFLittleHelperButton : HFBorderLineButton@property (copy, nonatomic) void (^action)();+ (id)buttonWithNormalTitle:(NSString *)title action:(void(^)(void))action;@end
關鍵方法已做標註 了 重點 應該看如何調用的 這個.action方法 也可以在需要的地方擷取 這個 實施的btn對象 在需要到的地方 然後觸發.action()都可以
//// HFLittleHelperButton.m// dailylife//// Created by HF on 15/12/5.////#import "HFLittleHelperButton.h"@implementation HFLittleHelperButton+ (id)buttonWithNormalTitle:(NSString *)title action:(void(^)(void))action{ HFLittleHelperButton *btn = [HFLittleHelperButton buttonWithType:UIButtonTypeCustom]; [btn setTitle:title forState:UIControlStateNormal]; [btn setTitleColor:COLOR_THEME_GREEN forState:UIControlStateNormal]; [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted]; [btn setBackgroundImage:[HuofarUtils createImageWithColor: COLOR_THEME_GREEN] forState:UIControlStateHighlighted]; btn.backgroundCustomColor = COLOR_THEME_GREEN; btn.layer.cornerRadius = 2; btn.layer.masksToBounds = YES; btn.layer.borderColor = COLOR_THEME_GREEN.CGColor; btn.layer.borderWidth = 1; [btn setAction:action];
[btn addTarget:self action:@selector(btnBlockAction:) forControlEvents:UIControlEventTouchUpInside];
return btn;}
- (void)btnBlockAction:(HFLittleHelperButton *)btn{
if(btn.action)
btn.action();
}
@end
實戰:
HFLittleHelperAlertView *alert = [[HFLittleHelperAlertView alloc]initWithBlockExpression:HelperAlertViewExpressionTypePlease Title:@"標題名稱" message:@"好好學習天天向上好好學習天天向上好好學習天天向上好好學習天天向上好好學習天天向上好好學習天天向上" withView:nil cancelButton:[HFLittleHelperButton buttonWithCancelTitle:@"取消" action:^{ NSLog(@"XXXXXX"); }] otherButtons:[HFLittleHelperButton buttonWithNormalTitle:@"111111" action:^{ NSLog(@"111111"); }],[HFLittleHelperButton buttonWithNormalTitle:@"222222" action:^{ NSLog(@"222222"); }],[HFLittleHelperButton buttonWithNormalTitle:@"333333" action:^{ NSLog(@"333333"); }],nil]; [alert showHelperAlertViewView];
iOS 嘗試用 block 閉包 去代替delegate 實現方法