Ios 有人把UIActionSheet(buttonIndex,delegate)做得更像UIButton(addTarget:action)了吗?
我看到马可·阿尔芒: 子类化Ios 有人把UIActionSheet(buttonIndex,delegate)做得更像UIButton(addTarget:action)了吗?,ios,uibutton,uiactionsheet,Ios,Uibutton,Uiactionsheet,我看到马可·阿尔芒: 子类化UIActionSheet w/target:action:userInfo:按钮,以避免委托/按钮索引。不是别人干的吗?找不到 我认为这听起来是个好主意,但我找不到任何人的代码来实现这一点。在我亲自动手之前,有人知道吗?是的,请查看我的github 它是使用块实现的,因此您可以这样使用它,即使不在源代码中删除目标/操作代码,最大的优点是所有内容都位于源代码中的同一位置,并且您可以在同一控制器中使用任意数量的OHActionSheets NSURL* anURL =
UIActionSheet w/target:action:userInfo:
按钮,以避免委托/按钮索引。不是别人干的吗?找不到
我认为这听起来是个好主意,但我找不到任何人的代码来实现这一点。在我亲自动手之前,有人知道吗?是的,请查看我的github
它是使用块实现的,因此您可以这样使用它,即使不在源代码中删除目标/操作代码,最大的优点是所有内容都位于源代码中的同一位置,并且您可以在同一控制器中使用任意数量的OHActionSheets
NSURL* anURL = ... // some URL (this is only as an example on using out-of-scope variables in blocks)
[OHActionSheet showSheetInView:yourView
title:@"Open this URL?"
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:[NSArray arrayWithObjects:@"Open",@"Bookmark",nil]
completion:^(OHActionSheet* sheet,NSInteger buttonIndex) {
if (buttonIndex == sheet.cancelButtonIndex) {
NSLog(@"You cancelled");
} else {
NSLog(@"You choosed button %d",buttonIndex);
switch (buttonIndex-sheet.firstOtherButtonIndex) {
case 0: // Open
// here you can access the anURL variable even if this code is executed asynchrously, thanks to the magic of blocks!
[[UIApplication sharedApplication] openURL:anURL];
break;
case 1: // Bookmark
default:
// Here you can even embed another OHAlertView for example
[OHAlertView showAlertWithTitle:@"Wooops"
message:@"This feature is not available yet, sorry!"
cancelButton:@"Damn"
otherButtons:nil
onButtonTapped:nil]; // no need for a completion block here
break;
} // switch
}
}];
[编辑]编辑示例代码以添加更多详细信息和用法示例看起来不错,但如果要继续操作,您仍然需要定义按钮标题数组,根据索引获取这些标题,然后将它们转换为选择器。我希望它更像是
UIButton
,我只需要一次定义标题、选择器和目标。我喜欢blocks方法的一点是,你可以通过相同的UIBarButtonItem轻松地显示后续的动作表,因为你在显示第一个动作表时就知道了。(我不知道用普通的UIActionSheet做这件事的好方法。)(我想传递动作的原因是我在多个视图控制器中使用了一个动作表,它们都会响应。)解决方案的一个示例:您可以定义一个包含NSDictionary的NSArray*btnDefs
,每个NSDictionary
都有一个键@“title”
和一个键@“selector”
。然后使用KVC工具,使用[btnDefs-valueForKey:@“title”]
作为otherbuttonitles
参数,并在completionBlock的代码中,使用sthg-likeNSString*selectorName=[[btnDefs-objectAtIndex:buttonIndex-sheet.firstOtherButtonIndex]objectForKey:@“selector”]
,然后SEL selector=NSSelectorFromString(selectorName)
获取选择器,最后[自执行选择器:选择器]代码>使用OHActionSheet/脚本执行它。他们真的很棒。谢谢分享。