使用6个以上的自定义按钮时,UIActionSheet buttonIndex值是否有问题?

hue*_*ice 25 iphone uiactionsheet ios

我在iPhone(iOS 4.2)上使用UIActionSheet时发现了一个奇怪的问题.考虑以下代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    UIActionSheet *actionSheet = [[UIActionSheet alloc] 
                                  initWithTitle:@"TestSheet" 
                                  delegate:self 
                                  cancelButtonTitle:@"Cancel" 
                                  destructiveButtonTitle:nil 
                                  otherButtonTitles: nil];

    [actionSheet addButtonWithTitle:@"one"];
    [actionSheet addButtonWithTitle:@"two"];
    [actionSheet addButtonWithTitle:@"three"];
    [actionSheet addButtonWithTitle:@"four"];
    [actionSheet addButtonWithTitle:@"five"];
    [actionSheet addButtonWithTitle:@"six"];
    //uncomment next line to see the problem in action
    //[actionSheet addButtonWithTitle:@"seven"];

    [actionSheet showInView:window];
    [actionSheet release];

    return YES;
}
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"buttonIndex: %d, cancelButtonIndex: %d, firstOtherButtonIndex: %d",
          buttonIndex, 
          actionSheet.cancelButtonIndex, 
          actionSheet.firstOtherButtonIndex);
}
Run Code Online (Sandbox Code Playgroud)

如果启动此应用程序,则操作表将按预期运行.这意味着cancelButtonIndex始终为0,并且正确报告按钮索引.按钮"1"依次为1,依此类推.如果您在添加第七个按钮的行中注释,则操作表会生成一种tableview,并在额外的行上显示取消按钮.如果在这种情况下我按下"one"按钮,则buttonindex变量为0,但cancelButtonIndex也是如此.无法判断用户是否已点击"取消"或"一个"按钮.这似乎不应该是这样的.有人不同意吗?谢谢你的帮助.

Ric*_*ers 34

我遇到了同样的问题,即使我已经将取消按钮作为操作表中的最后一个并相应地设置其索引.我的问题与"破坏性"按钮有关.经过一番调查,这是我对这个问题的看法:

  • 将N个按钮添加到操作表后,它会切换其布局,将"破坏性"按钮置于顶部,将"取消"按钮置于底部.中间是一个包含所有其他按钮的可滚动视图.其他来源表明这是一个表格视图.

  • 纵向方向的N为7,横向方向的N为5.在较大的4英寸屏幕上,N为9表示纵向.这些数字适用于所有按钮,包括取消和破坏性.要清楚,N是切换前最大的按钮数.N + 1按钮使UIActionSheet切换到可滚动视图.

  • 您最初在操作表中放置取消和破坏性按钮的操作表中的位置并不重要.达到限制后,"破坏性"按钮将移至顶部,"取消"将移至底部.

  • 问题是指数没有相应调整.因此,如果您最初没有将Cancel作为最后一个按钮并将Destructive作为第一个按钮添加,则将在actionSheet中报告错误的索引:clickedButtonAtIndex:如初始报告所述.

  • 因此,如果您在操作表中有超过N个按钮,则必须将"破坏性"按钮添加到actionSheet作为操作表的第一个按钮.您必须添加取消按钮作为添加到操作表的最后一个按钮.在最初构建工作表时,只需将两者都保留为零,如另一个答案中所述.

  • 这是一种荒谬的行为.我经常想知道为什么Apple做出某些决定.这是其中之一.谢谢你的提示. (5认同)

小智 13

我刚遇到这个问题.通过最初不设置取消按钮来解决它.我单独设置按钮是这样的:

   for(int index = 0; index < buttonTotal; index++)
   {
    [actionSheet addButtonWithTitle:[NSString stringWithFormat:buttonText, [buttonItems objectAtIndex: index]]];
   }

   [actionSheet addButtonWithTitle:@"Cancel"];
   actionSheet.cancelButtonIndex = actionSheet.numberOfButtons;
Run Code Online (Sandbox Code Playgroud)

我相信如果你使用它,那么destructiveButton会使用零索引,所以其他按钮将从那里开始增加,否则它们将从0开始.

不确定我同意表选项,因为超过一定数量,按钮默认为可滚动列表.

  • 你应该做`actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"取消"]; (18认同)