簡體   English   中英

按下取消時顯示警報視圖並停留在同一視圖控制器上

[英]Show alert view and stay on same view controller when cancel is pushed

我正在使用故事板,其中兩個視圖控制器通過segue相互連接。 在第一個視圖控制器上有一個按鈕,如果您單擊該按鈕,它將轉到第二個視圖控制器。 問題是我想彈出一個警報視圖,我試圖在- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender方法中顯示警報視圖,但是問題在於它轉到了第二個視圖控制器,然后彈出警報視圖。 我希望它在第一個視圖控制器上彈出,並且如果您從警報視圖中按“取消”按鈕,它仍然停留在第一個視圖控制器上。 知道我該怎么做嗎?

您需要通過單擊按鈕來顯示警報,並充當警報的委托。 僅當您收到警報完成委托回調(alertView:willDismissWithButtonIndex :)時,您才決定是應該觸發segue還是不執行任何操作。

為此,您需要執行以下操作:

  • 從故事板上的按鈕上刪除標記。
  • 為該按鈕實現IBAction並在那里顯示警報
  • 使用clickedButtonAtIndex的委托方法UIAlertView檢查按下按鈕。 如果用戶按確定轉到下一個視圖

像這樣添加IBAction

- (IBAction)showAlert:(id)sender
{
   UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Can I Move ?"
                                                  message:nil
                                                 delegate:self
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:@"Cancel",nil];
   [message show];
}

並實現如下的委托方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"OK"])
    {
        [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"Other View"] animated:YES];
    }
}

注意:您也可以使用performSegueWithIdentifier移至下一個視圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM