通过传入数组而不是 varlist 创建 UIActionsheet‘ other Buttons’

我有一个字符串数组,我想用于 UIActionsheet 上的按钮标题。遗憾的是,方法调用中的 other ButtonTitles: 参数接受字符串的可变长度列表,而不是数组。

那么如何将这些标题传递到 UIActionsheet 中呢?我看到的解决方法是将 nil 传递给 other ButtonTitles: ,然后使用 addButtonWithTitle: 分别指定按钮标题。但是这样会出现一个问题: 将“ Cancel”按钮移动到 UIActionsheet 中的第一个位置而不是最后一个位置; 我希望它是最后一个。

有没有办法1)传递一个数组来代替字符串的变量列表,或者2)将取消按钮移动到 UIActionsheet 的底部?

谢谢。

28065 次浏览

I got this to work (you just need to, be ok with a regular button, and just add it after :

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];

One little note: [actionSheet addButtonWithTitle:] returns the index of that button, so to be safe and "clean" you can do this:

actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];

Taking Jaba's and Nick's answers and extending them a little further. To incorporate a destruction button into this solution:

// 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];

There is the swift version for the response :

//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)

To get value selected, add delegate to your ViewController :

class MyViewController: UIViewController, UIActionSheetDelegate

And implement the method "clickedButtonAtIndex"

func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
let selectedValue : String = values[buttonIndex]
}