简体   繁体   English

取消按钮和UIActionSheet的问题

[英]Problems with Cancel Button and UIActionSheet

How do I determine if the cancel button was pressed on a UIActionSheet? 如何确定UIActionSheet上是否按下了取消按钮?

My UIActionSheet is set up like this: 我的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];

}

The problem that I have is that I cannot differentiate between the cancel button and the first button selected. 我遇到的问题是我无法区分取消按钮和所选的第一个按钮。

-(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.
}

Is there a better way of setting this up? 有没有更好的方法来设置它?

The trick turns out to be not to use the automatic cancel button but to add it yourself. 诀窍是不使用自动取消按钮,而是自己添加。

The other slight gotcha is to add the cancel button at the end and not at the beginning. 另一个小问题是在结尾而不是在开头添加取消按钮。

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

credit to this stackoverflow entry for the answer. 归功于此stackoverflow条目的答案。

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

UIActionSheet also has properties like destructiveButtonIndex and firstOtherButtonIndex to compare against. UIActionSheet还具有destructiveButtonIndexfirstOtherButtonIndex等属性进行比较。

add this 加上这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM