歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS UIAlertview的事件處理

iOS UIAlertview的事件處理

日期:2017/3/1 10:19:28   编辑:Linux編程

1.開始想用UIView做密碼輸入

2.後來覺得麻煩,改用UIAlertview

3.因為我做的是SBSETTINGS開發,不能提供UIAlertView 事件處理所需要的self.說到這個UIAlertView不得不吐槽一下,APPLE絕對是極限方便使用者,非常虐待開發者的.

為了保證流暢,連UIAlertView的YES NO事件都TNND要delegate

UIAlertView和UIActionSheet都采用了Delegate模式,在同一個視圖控制器中使用多個UIAlertView或UIActionSheet時控制器需要同時充當它們的delegate,這種情況下處理函數中通常需要通過tag進行區分後處理。這樣就經常會造成如下代碼:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if ([alertView tag] == LOGIN_ERROR_ALERT) { // it's alert for login error
if (buttonIndex == 0) { // and they clicked OK.
// do stuff
}
}
else if ([alertView tag] == UPDATE_ERROR_ALERT) { // it's alert for update error
if (buttonIndex == 0) { // and they clicked OK.
// do stuff
}
}
else {
}
}

4.這回郁悶了,無法直接用上面的方式處理按鈕事件.想想我肯定不是第一個倒霉孩子,果然給我找到一種UIAlsertview block方式
簡單來說,這其實就是把按鈕事件封裝成一個方法塊(這說法不嚴謹),然後把這個塊做為參數傳遞給UIAlertView.實際上還是回調,不過要容易理解也容易處理些.

代理在 https://github.com/jivadevoe/UIAlertView-Blocks

先寫好方法塊

RIButtonItem *cancelItem = [RIButtonItem item];
cancelItem.label = @"No";
cancelItem.action = ^
{
//為NO時的處理
};

RIButtonItem *deleteItem = [RIButtonItem item];
deleteItem.label = @"Yes";
deleteItem.action = ^
{
//為YES時的處理
[context deleteObject:theObject];
};
//調用

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Delete This Item?"
message:@"Are you sure you want to delete this really important thing?"
cancelButtonItem:cancelItem
otherButtonItems:deleteItem, nil];
[alertView show];

別忘記

#include "RIButtonItem.h"
#include "UIAlertView+Blocks.h"

Copyright © Linux教程網 All Rights Reserved