如何在if语句中使用UIActionSheet?

时间:2014-02-22 01:13:31

标签: ios objective-c cocoa-touch

我有一个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对象。有没有更简单的方法来做到这一点,或者我应该只将标题作为全局变量?

2 个答案:

答案 0 :(得分:1)

尝试

- (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];
    }
}

答案 1 :(得分:1)

UIActionSheet不是那样使用的:

- (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");
}

你必须明白界面元素不是“即时”的,还有很多不同步的东西。例如,当呈现UIActionSheet时,线程不会等待用户回答是或否,它会继续运行。

这就是为什么会有代表和块,你出示UIActionSheet,并且代表你说“我会在用户实际点击它时处理它”。

你想知道,为什么不等它选择呢?主线程负责更新界面,动画和检索用户输入(触摸,键盘点击等),甚至运行NSTimers作为主NSRunLoop的下标。停止主线程将锁定接口。