需求是:使用者完成某個手勢操作(例如右滑)之後,先跳出一個 UIAlertView 詢問「確定要送出嗎?」,只有按下確定才真的執行提交。直接寫卻沒有反應,問題通常出在 delegate 的設定時機與按鈕索引的判斷上。
UISwipeGestureRecognizer *gesture =
[[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(didSwipeRight:)];
gesture.direction = UISwipeGestureRecognizerDirectionRight;
[yourView addGestureRecognizer:gesture];
方向可選 Up、Down、Left、Right 四種。一個 view 可以掛多個不同方向的辨識器,彼此不衝突。
- (void)didSwipeRight:(UIGestureRecognizer *)gestureRecognizer {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
message:@"Are you sure to commit with its action"
delegate:self
cancelButtonTitle:CKString(@"NO")
otherButtonTitles:CKString(@"YES"), nil];
alert.tag = 222;
[alert show];
}
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 222) {
if (buttonIndex == alertView.cancelButtonIndex) {
// 按下 NO
} else {
// 按下 YES,執行提交
}
}
}
1. 用 cancelButtonIndex 取代寫死的數字。 範例中寫 buttonIndex == 1 判斷「確定」,這很脆弱:一旦日後調整了 cancelButtonTitle 與 otherButtonTitles 的順序,判斷就會反過來。UIAlertView 提供了 cancelButtonIndex 與 firstOtherButtonIndex,用它們才不會出錯。
2. tag 的用途。 同一個類別若有多個不同用途的 alert,用 tag 區分是必要的;但若只有一個,就不需要。更乾淨的做法是拆成不同的 delegate 物件,或改用下面的 modern 寫法。
3. ARC 下不要 release。 原始範例寫於 MRC 時代,在 ARC 專案中呼叫 [alert release] 會直接編譯失敗。alert 由 show 之後的系統持有,去掉即可。
UIAlertView 自 iOS 8 起已被標記為廢棄(deprecated),新專案請改用 UIAlertController。它最大的好處是用 block 取代 delegate,不需要 tag、不需要多個回呼方法:
- (void)didSwipeRight:(UIGestureRecognizer *)gestureRecognizer {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:nil
message:@"確定要送出嗎?"
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel handler:^(UIAlertAction *a) {
NSLog(@"使用者取消");
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleDefault handler:^(UIAlertAction *a) {
[self submitAction]; // 真正執行提交
}]];
[self presentViewController:alert animated:YES completion:nil];
}
這樣寫不但少了 delegate 與 tag 的往來,每個按鈕的行為就寫在自己旁邊,可讀性高得多,也不容易搞錯索引。
若你的 view 位於 UIScrollView 內,或同時有 UITapGestureRecognizer,滑動手勢可能互相搶事件。此時可實作 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: 回傳 YES,或透過 requireGestureRecognizerToFail: 建立優先順序。