2011-03-02 153 views
12

如何確定取消按鈕是否在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]; 

} 

我已經是我無法取消按鈕和選擇的第一個按鈕區分的問題。

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

有沒有更好的設置方法?

回答

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條目答案。

+0

非常好,謝謝 – shannoga 2013-10-30 15:19:54

+1

UIActionSheet必須是所有iOS中最繁瑣的一段代碼 – bugfixr 2014-02-17 13:04:20

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

UIActionSheet也有像destructiveButtonIndexfirstOtherButtonIndex特性來比較。

+1

對不起,我不認爲我正確地問了我的問題。問題是,列表中的第一個按鈕返回零的buttonIndex,它被誤認爲是cancelButtonIndex操作。你知道我做錯了什麼嗎?謝謝。 – iphaaw 2011-03-23 13:00:58

+0

看起來像正確的方式,以便操作系統可以做所有它想要的取消按鈕(不同的分組,風格等)的特殊事情。 – eselk 2014-12-04 16:54:44

+0

這完全返回正確的取消索引值。 – tounaobun 2015-12-15 09:36:18

1

添加此

[MyMenu菜單showInView:self.parentViewController.tabBarController.view];