取消按钮和UIActionSheet出现问题

12

如何确定在UIActionSheet上按下的按钮是取消按钮?

我的UIActionSheet设置如下:

-(IBAction)fileButtonPressed
{
    UIActionSheet *mymenu = [[UIActionSheet alloc] 
                             initWithTitle:@"Select Folder" 
                             delegate:self 
                             cancelButtonTitle:@"Cancel" 
                             destructiveButtonTitle:nil 
                             otherButtonTitles:nil];

    for (i=0; i<3; i++) 
    { 
        [mymenu addButtonWithTitle:@"Button Name"]; 
    }

    [mymenu showInView:self.view];

}

我的问题是我无法区分取消按钮和第一个选择的按钮。

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{  
    NSString *option = [actionSheet buttonTitleAtIndex:buttonIndex];

    //buttonIndex == 0 if the cancel button is pressed or 
    //if the first item is pressed.
}

有更好的设置方法吗?

3个回答

31

窍门在于不要使用自动取消按钮,而是自己添加。

另一个小细节是在末尾而不是开头添加取消按钮。

-(IBAction)fileButtonPressed
{
    UIActionSheet *mymenu = [[UIActionSheet alloc] 
                             initWithTitle:@"Select Folder" 
                             delegate:self 
                             cancelButtonTitle:nil 
                             destructiveButtonTitle:nil 
                             otherButtonTitles:nil];
    for (int nb=0; nb<3; nb++) 
    { 
        [mymenu addButtonWithTitle:@"Button Name"]; 
    }

    mymenu.cancelButtonIndex = [mymenu addButtonWithTitle: @"Cancel"];

    [mymenu showInView:self.view];
}

感谢这篇stackoverflow文章提供的答案。


1
UIActionSheet一定是iOS中最有bug的代码片段。 - bugfixr

16
if (buttonIndex == actionSheet.cancelButtonIndex)
{
    // Handle cancel action
}

UIActionSheet 还有像 destructiveButtonIndexfirstOtherButtonIndex 这样的属性可以进行比较。


1
抱歉,我觉得我没有正确地提出我的问题。问题在于列表中的第一个按钮返回零的buttonIndex,这被误认为是cancelButtonIndex操作。你知道我做错了什么吗?谢谢。 - iphaaw
看起来这是正确的方式,这样操作系统就可以为取消按钮执行所有特殊的操作(不同的分组、样式等)。 - eselk
这将确切地返回正确的取消索引值。 - tounaobun

1

添加这个

[mymenu showInView:self.parentViewController.tabBarController.view];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接