Создать UIActionSheet 'otherButtons', передав массив, а не varlist
У меня есть массив строк, который я хочу использовать для названий кнопок на UIActionSheet. К сожалению, аргумент otherButtonTitles: в вызове метода принимает переменную длину строк, а не массив.
Итак, как я могу передать эти заголовки в UIActionSheet? Обходной путь, который я видел, это передать нить в otherButtonTitles:, затем указать названия кнопок отдельно, используя addButtonWithTitle:. Но в этом проблема заключается в перемещении кнопки "Отмена" в первую позицию на UIActionSheet, а не в последнюю; Я хочу, чтобы он был последним.
Есть ли способ: 1) передать массив вместо переменного списка строк или, альтернативно, 2) переместить кнопку отмены в нижней части таблицы UIActionSheet?
Спасибо.
Ответы
Ответ 1
Я получил это на работу (вам просто нужно быть в порядке с обычной кнопкой и просто добавить его после:
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];
Ответ 2
Одна маленькая заметка: [actionSheet addButtonWithTitle:] возвращает индекс этой кнопки, поэтому для обеспечения безопасности и "очистки" вы можете сделать это:
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
Ответ 3
Взятие Джабы и Ника отвечает и расширяет их немного дальше. Чтобы включить в это решение кнопку уничтожения:
// 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];
Ответ 4
Существует быстрая версия для ответа:
//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]
}