我有一个字符串数组,我想用于UIActionSheet上的按钮标题。不幸的是,方法调用中的otherButtonTitles:参数采用可变长度的字符串列表,而不是数组。
那我怎么能把这些标题传递到UIActionSheet呢?我见过的解决方法是将nil传递给otherButtonTitles :,然后使用addButtonWithTitle:单独指定按钮标题。但这有将“取消”按钮移动到UIActionSheet上的第一个位置而不是最后一个位置的问题;我希望它是最后一个。
有没有办法1)传递数组代替变量字符串列表,或者2)将取消按钮移动到UIActionSheet的底部?
感谢。
答案 0 :(得分:246)
我让这个工作(你只需要,可以使用常规按钮,然后在以下后添加:
NSArray *array = @[@"1st Button",@"2nd Button",@"3rd Button",@"4th Button"];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Title Here"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
// ObjC Fast Enumeration
for (NSString *title in array) {
[actionSheet addButtonWithTitle:title];
}
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
[actionSheet showInView:self.view];
答案 1 :(得分:78)
一个小注意事项:[actionSheet addButtonWithTitle:]返回该按钮的索引,因此为了安全起见并“干净”,您可以这样做:
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
答案 2 :(得分:3)
采取Jaba和Nick的答案并进一步扩展它们。要在此解决方案中加入销毁按钮:
// Create action sheet
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
// Action Buttons
for (NSString *actionName in actionNames){
[actionSheet addButtonWithTitle: actionName];
}
// Destruction Button
if (destructiveName.length > 0){
[actionSheet setDestructiveButtonIndex:[actionSheet addButtonWithTitle: destructiveName]];
}
// Cancel Button
[actionSheet setCancelButtonIndex: [actionSheet addButtonWithTitle:@"Cancel"]];
// Present Action Sheet
[actionSheet showInView: self.view];
答案 3 :(得分:1)
响应的快速版本:
//array with button titles
private var values = ["Value 1", "Value 2", "Value 3"]
//create action sheet
let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: nil, destructiveButtonTitle: nil)
//for each value in array
for value in values{
//add a button
actionSheet.addButtonWithTitle(value as String)
}
//display action sheet
actionSheet.showInView(self.view)
要选择值,请将委托添加到ViewController:
class MyViewController: UIViewController, UIActionSheetDelegate
实现方法“clickedButtonAtIndex”
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
let selectedValue : String = values[buttonIndex]
}