[英]iOS alertview action on a button
我在菜單中有一個按鈕,當觸摸時,會彈出一個警告消息,其中包含兩個按鈕:“ Cancel
”和“ Yes
”。 這是我對警報的代碼:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game"
message:@"Are you sure?"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Yes", nil];
[alert show];
是否可以在“ Yes
”按鈕上添加動作?
在您的代碼中設置UIAlertView委托:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show];
正如您已將委托設置為self,請在同一個類中編寫委托函數,如下所示:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) { // Set buttonIndex == 0 to handel "Ok"/"Yes" button response
// Cancel button response
}}
您需要實現UIAlertViewDelegate
並添加以下內容......
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
// do stuff
}
}
是的,很容易。 看到你現在設置為nil的名為“delegate”的參數? 將其設置為對象...如果從視圖控制器調用它,則通常為“self”,然后為UIAlertViewDelegate實現選擇器。
您還需要聲明視圖控制器符合UIAlertViewDelegate協議。 這樣做的好地方是視圖控制器的“私有”延續類。
@interface MyViewController() <UIAlertViewDelegate>
@end
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"Button pushed: %d", buttonIndex);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.