如何在if语句中使用UIActionSheet?

我有一个if语句工作正常,但我需要添加一个第二if语句里面,我似乎无法弄清楚如何得到它的权利。

这是我的代码:

 -(IBAction)xButton { if([_hasUserTakenAPhoto isEqual: @"YES"]) { _xButtonAfterPhotoTaken = [[UIActionSheet alloc] initWithTitle:@"Delete" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil]; [_xButtonAfterPhotoTaken showInView:self.view]; NSString *title = [_xButtonAfterPhotoTaken buttonTitleAtIndex:1]; if(title isEqualToString:@"Delete") { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } } else { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } } 

当我添加第二条if语句时,出现错误:

 if(title isEqualToString:@"Delete") { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } 

我试图让第二个if语句是“else if”,但是不会让我访问名为“title”的NSString对象。 有一个更简单的方法来做到这一点,或者我应该只是使标题全球variables?

UIActionSheet s不是这样使用的:

 - (IBAction)xButton:(UIButton*)sender { if ([_hasUserTakenAPhoto isEqual:@"YES"]) { _xButtonAfterPhotoTaken = [[UIActionSheet alloc] initWithTitle:@"Delete Photo?" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:nil]; [_xButtonAfterPhotoTaken showInView:self.view]; } else { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } } - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { // Check if it's the correct action sheet and the delete button (the only one) has been selected. if (actionSheet == _xButtonAfterPhotoTaken && buttonIndex == 0) { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } } - (void)actionSheetCancel:(UIActionSheet *)actionSheet { NSLog(@"Canceled"); } 

你必须明白,界面元素不是“即时”的,有大量的asynchronous进行。 例如,当呈现UIActionSheet ,线程不会等待用户回答“是”或“否”,而是继续运行。

这就是为什么有代表和块,你提交UIActionSheet ,并与代表你说:“我会照顾它,当用户实际上点击它”。

你会想知道,为什么不直接select呢? 主线程负责更新接口,animation和检索用户input(触摸,键盘敲击等),甚至运行下标到主NSRunLoop 。 停止主线程会locking接口。

尝试

 - (IBAction)xButton { NSString *title; if ([_hasUserTakenAPhoto isEqual:@"YES"]) { _xButtonAfterPhotoTaken = [[UIActionSheet alloc] initWithTitle:@"Delete" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil]; [_xButtonAfterPhotoTaken showInView:self.view]; title = [_xButtonAfterPhotoTaken buttonTitleAtIndex:1]; if ([title isEqualToString:@"Delete"]) { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } } else { [self performSegueWithIdentifier:@"backToHomeFromMediaCaptureVC" sender:self]; } }