Ste*_*her 54 iphone nsarray uialertsheet
UIAlertSheet的构造函数将otherButtonTitles参数作为varg列表.我想指定NSArray中的其他按钮标题.这可能吗?
即我必须这样做:
id alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: button1Title, button2Title, nil];
Run Code Online (Sandbox Code Playgroud)
但由于我在运行时生成可用按钮列表,我真的想要这样的东西:
id alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: otherButtonTitles];
Run Code Online (Sandbox Code Playgroud)
现在,我想我需要单独拨打一个initWithTitle:项目,2个项目和3个项目.像这样:
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
}
Run Code Online (Sandbox Code Playgroud)
这是很多重复的代码,但它实际上可能是合理的,因为我最多有三个按钮.我怎么能避免这个?
Eph*_*aim 72
这是一年了,但解决方案非常简单...按照@Simon建议,但不指定取消按钮标题,所以:
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: nil
destructiveButtonTitle: nil
otherButtonTitles: nil];
Run Code Online (Sandbox Code Playgroud)
但添加正常按钮后,添加取消按钮,如:
for( NSString *title in titles) {
[alert addButtonWithTitle:title];
}
[alert addButtonWithTitle:cancelString];
Run Code Online (Sandbox Code Playgroud)
现在关键的一步是指定哪个按钮是取消按钮,如:
alert.cancelButtonIndex = [titles count];
Run Code Online (Sandbox Code Playgroud)
我们这样做,[titles count]而不是[titles count] - 1因为我们在按钮列表中添加取消按钮作为额外按钮titles.
您现在还可以通过指定destructiveButtonIndex(通常是按钮)来指定您想要成为破坏性按钮的按钮(即红色[titles count] - 1按钮).此外,如果您将取消按钮保持为最后一个按钮,iOS将在其他按钮和取消按钮之间添加漂亮的间距.
所有这些都是iOS 2.0兼容所以享受.
Sim*_*mon 52
在初始化UIActionSheet时,不要添加按钮,而是使用通过NSArray的for循环,使用addButtonWithTitle方法添加它们.
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: nil];
for( NSString *title in titles)
[alert addButtonWithTitle:title];
Run Code Online (Sandbox Code Playgroud)
addButtonWithTitle:返回添加按钮的索引.在init方法中将cancelButtonTitle设置为nil,并在添加其他按钮后运行:
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
Run Code Online (Sandbox Code Playgroud)