取消按钮和UIActionSheet的问题

iph*_*aaw 12 iphone uiactionsheet

如何确定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];

}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我无法区分取消按钮和所选的第一个按钮.

-(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.
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来设置它?

iph*_*aaw 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];
}
Run Code Online (Sandbox Code Playgroud)

归功于此stackoverflow条目的答案.


Mar*_*ams 16

if (buttonIndex == actionSheet.cancelButtonIndex)
{
    // Handle cancel action
}
Run Code Online (Sandbox Code Playgroud)

UIActionSheet还具有喜欢destructiveButtonIndexfirstOtherButtonIndex比较的属性.