UIActionSheet混乱的优雅解决方案

Spa*_*Dog 4 iphone ipad ios

我试图找到一个优雅的UIActionSheet问题的解决方案.

我像这样使用UIActionSheets:

UIActionSheet * myChoices = [[UIActionSheet alloc]
    initWithTitle:nil
    delegate:self
    cancelButtonTitle:@"cancel"
    destructiveButtonTitle:@"erase"
    otherButtonTitles: @"aaa", @"bbb", @"ccc", @"ddd", nil]; 
Run Code Online (Sandbox Code Playgroud)

问题是,为了发现用户选择的选项,我必须使用:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    switch ([actionSheet tag]) {
           case 0: ... 
           case 1: ... 
           case 2: ... 
           case 3: ... 

        }
}
Run Code Online (Sandbox Code Playgroud)

基于索引的这种情况很可怕,因为如果我改变了aaa,bbb,ccc等的顺序,我必须在动作表上更改大小写顺序.这个索引的东西并不是一个可靠的解决方案.

我试图想象一种方法来做到这一点,并成为独立于索引但没有得到任何满意的解决方案.使用buttonTitleAtIndex也不够好,因为我的应用程序是本地化的,我必须为每个条目测试n个标题.有什么建议?

Ali*_*are 5

我公司自创建的基于块的版本UIAlertViewUIActionSheet,我个人从来没有再次使用基于委托的苹果版本.
您可以在我的GitHub存储库中下载我的OHActionSheetOHAlertView.

因为它们基于completionBlock模式,所以它们更具可读性(所有代码都在同一个地方,没有多个公共委托UIActionSheets,......),并且功能更强大(因为块也可以根据需要捕获它们的上下文).

NSArray* otherButtons = @[ @"aaa", @"bbb", @"ccc", @"ddd" ];
[OHActionSheet showSheetInView:self.view
                         title:nil
             cancelButtonTitle:@"cancel"
        destructiveButtonTitle:@"erase"
             otherButtonTitles:otherButtons
        completion:^(OHActionSheet* sheet, NSInteger buttonIndex)
 {
   if (buttonIndex == sheet.cancelButtonIndex) {
     // cancel
   } else if (buttonIndex == sheet.destructiveButtonIndex) {
     // erase
   } else {
     NSUInteger idx = buttonIndex - sheet.firstOtherButtonIndex;
     // Some magic here: thanks to the blocks capturing capability,
     // the "otherButtons" array is accessible in the completion block!
     NSString* buttonName = otherButtons[idx];
     // Do whatever you want with idx and buttonName
   }
 }];
Run Code Online (Sandbox Code Playgroud)

附加说明:如何switch/case在NSStrings上

需要注意的是,在的otherButtons部分if/else在完成处理程序测试,然后,您可以测试的idx使用switch/case,或使用我的ObjcSwitch类别,这将允许你写switch/case般的代码,但为NSStrings,所以你可以在这样的代码你OHActionSheet的完成处理程序:

NSUInteger idx = buttonIndex - sheet.firstOtherButtonIndex;
NSString* buttonName = otherButtons[idx];
[buttonName switchCase:
   @"aaa", ^{ /* Some code here to execute for the "aaa" button */ },
   @"bbb", ^{ /* Some code here to execute for the "bbb" button */ },
   @"ccc", ^{ /* Some code here to execute for the "ccc" button */ },
   ..., nil
];
Run Code Online (Sandbox Code Playgroud)

编辑:既然最新的LLVM编译器支持新的"对象文字"语法,你可以像ObjcSwitch使用NSDictionary的紧凑语法一样:

((dispatch_block_t)@{
   @"aaa": ^{ /* Some code here to execute for the "aaa" button */ },
   @"bbb": ^{ /* Some code here to execute for the "bbb" button */ },
   @"ccc": ^{ /* Some code here to execute for the "ccc" button */ },
}[buttonName] ?:^{
       /* Some code here to execute for defaults if no case found above */
})();
Run Code Online (Sandbox Code Playgroud)