UIAlertSheet的构造函数接受一个otherButtonTitles参数作为varg列表。我想从NSArray中指定其他按钮的标题。这个是可能的吗?
例如,我必须这样做:
id alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: button1Title, button2Title, nil];
但由于我是在运行时生成可用按钮的列表,所以我真的想要这样的东西:
id alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: otherButtonTitles];
现在,我想我需要为1个项目、2个项目和3个项目分别调用initWithTitle:
。如下所示:
if ( [titles count] == 1 ) {
alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: [titles objectAtIndex: 0], nil];
} else if ( [titles count] == 2) {
alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: [titles objectAtIndex: 0], [titles objectAtIndex: 1], nil];
} else {
// and so on
}
这有很多重复的代码,但它实际上可能是合理的,因为我最多有三个按钮。我怎样才能避免这种情况?
发布于 2012-11-29 06:05:38
这已经有一年的历史了,但解决方案很简单……按照@Simon的建议执行操作,但不要指定cancel按钮标题,因此:
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: nil
destructiveButtonTitle: nil
otherButtonTitles: nil];
但在添加普通按钮后,添加取消按钮,如下所示:
for( NSString *title in titles) {
[alert addButtonWithTitle:title];
}
[alert addButtonWithTitle:cancelString];
现在,关键步骤是指定哪个按钮是cancel按钮,如下所示:
alert.cancelButtonIndex = [titles count];
我们执行[titles count]
而不是[titles count] - 1
,因为我们从titles
的按钮列表中添加了cancel按钮作为额外按钮。
现在,您还可以通过指定destructiveButtonIndex (通常是[titles count] - 1
按钮)来指定您希望哪个按钮成为破坏性按钮(即红色按钮)。此外,如果您将cancel按钮保留为最后一个按钮,iOS将在其他按钮和cancel按钮之间添加适当的间距。
所有这些都与iOS 2.0兼容,所以请尽情享受吧。
发布于 2009-10-22 01:23:30
与其在初始化UIActionSheet时添加按钮,不如尝试使用addButtonWithTitle方法添加它们,方法是使用遍历NSArray的for循环。
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: nil];
for( NSString *title in titles)
[alert addButtonWithTitle:title];
发布于 2013-08-24 13:21:15
addButtonWithTitle:返回添加的按钮的索引。在init方法中将cancelButtonTitle设置为nil,并在添加其他按钮后运行以下命令:
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
https://stackoverflow.com/questions/1602214
复制相似问题