【发布时间】:2009-10-26 15:26:06
【问题描述】:
我有一个应用程序的要求,我需要能够动态添加 otherButtonTitles,这取决于用户在设置中指定的一些 BOOL 开关。但是,我似乎无法弄清楚如何在 UIActionSheet 初始化中执行此操作。我尝试传递一个 NSString 数组(NSString[2]),以及一个 NSArray,但没有任何运气。
非常感谢这里的任何帮助。
【问题讨论】:
标签: iphone objective-c
我有一个应用程序的要求,我需要能够动态添加 otherButtonTitles,这取决于用户在设置中指定的一些 BOOL 开关。但是,我似乎无法弄清楚如何在 UIActionSheet 初始化中执行此操作。我尝试传递一个 NSString 数组(NSString[2]),以及一个 NSArray,但没有任何运气。
非常感谢这里的任何帮助。
【问题讨论】:
标签: iphone objective-c
我发现的最简单的方法是最初创建没有按钮的操作表,包括没有取消或破坏性按钮:
UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Dynamic"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
然后根据需要添加一堆按钮:
if(buttonX)
{
[actionSheet addButtonWithTitle:@"Button X"];
}
if(buttonY)
{
[actionSheet addButtonWithTitle:@"Button Y"];
}
if(buttonZ)
{
[actionSheet addButtonWithTitle:@"Button Z"];
}
然后最后在最后添加取消按钮并设置取消按钮索引:
[actionSheet addButtonWithTitle:@"Cancel"];
actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1;
当然,您可以通过这种方式同时添加取消按钮和/或破坏性按钮。
【讨论】:
您可以使用addButtonWithTitle: 方法向(已经初始化的)UIActionSheet 添加新按钮。您还可以创建自定义 UIButton 并将它们作为子视图添加到 UIActionSheet 的视图中
【讨论】:
addButtonWithTitle:,然后添加一个“取消”按钮作为最后一个,使用setCancelButtonIndex 来识别它。问题是,当您的按钮数量超出屏幕大小时,它会切换到 UITableView,并且按钮会变成表格中的单元格。如果您没有通过cancelButtonTitle 指定的实际取消按钮,则无法关闭工作表,因为没有按钮出现。此时您必须退出应用程序。有关示例,请参见这些屏幕:conceptcache.com/tmp/with_cancel_button.pngconceptcache.com/tmp/without_cancel_button.png
我最终通过使用一些零字符串和一个数组来解决这个问题。我将我需要的动态标题放在一个数组中,然后循环遍历它并根据需要设置具有尽可能多的标题的占位符字符串。然后在操作表初始化中将占位符字符串传递给otherButtonTitles:。 otherButtonTitles: 被 nil 终止,您可以根据需要传递尽可能多的占位符字符串,因为第一个 nil 占位符将终止其余的。
// button titles
NSMutableArray *buttons = [[NSMutableArray alloc] init];
[buttons addObject:@"Button 1"];
[buttons addObject:@"Button 2"];
// placeholders
NSString *button0 = nil, *button1 = nil, *button2 = nil;
// put together the buttons
for (int x = 0; x < buttons.count; x++) {
switch (x) {
case 0:
button0 = [buttons objectAtIndex:x];
break;
case 1:
button1 = [buttons objectAtIndex:x];
break;
case 2:
button2 = [buttons objectAtIndex:x];
break;
}
}
// action sheet
UIActionSheet *option = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:button0, button1, button2, nil];
希望这对面临类似困境的其他人有所帮助。
【讨论】:
如果您需要这么多按钮,请创建您自己的模式视图和您自己的委托协议。
查看presentModalViewController:animated 和dismissModalViewController:animated: 的文档
当用户关闭您的模态视图时,您的委托可以接收您构建的方法,例如 customActionSheetDidFinish:(int)buttonChosen
【讨论】: