Использовать NSArray для указания других заголовков кнопок?
-
05-07-2019 - |
Вопрос
Конструктор 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];
Прямо сейчас я думаю, что мне нужно сделать отдельный звонок, чтобы initWithTitle:
для 1 предмета, 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
}
Это много повторяющегося кода, но на самом деле это может быть разумно, поскольку у меня есть не более трех кнопок.Как я могу избежать этого?
Решение
Этому проекту уже год , но решение довольно простое ...сделайте, как предложил @Simon, но не указывайте название кнопки отмены, чтобы:
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];
Теперь ключевой шаг - указать, какая кнопка является кнопкой отмены, например:
alert.cancelButtonIndex = [titles count];
Мы делаем [titles count]
и не [titles count] - 1
поскольку мы добавляем кнопку "Отмена" как дополнительную из списка кнопок в titles
.
Теперь вы также указываете, какую кнопку вы хотите использовать в качестве деструктивной кнопки (т. Е. красной кнопки), указав destructiveButtonIndex (обычно это будет [titles count] - 1
кнопка).Кроме того, если вы оставите кнопку "Отмена" последней кнопкой, iOS добавит этот приятный интервал между другими кнопками и кнопкой "Отмена".
Все это совместимо с iOS 2.0, так что наслаждайтесь.
Другие советы
Вместо добавления кнопок при инициализации UIActionSheet попробуйте добавить их с помощью метода addButtonWithTitle, используя цикл for, который проходит через ваш NSArray.
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: nil];
for( NSString *title in titles)
[alert addButtonWithTitle:title];
addButtonWithTitle Добавить кнопку с заголовком:возвращает индекс добавленной кнопки.Установите cancelButtonTitle равным нулю в методе init и после добавления дополнительных кнопок запустите это:
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:@"Cancel"];
- (void)showActionSheetWithButtons:(NSArray *)buttons withTitle:(NSString *)title {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle: title
delegate: self
cancelButtonTitle: nil
destructiveButtonTitle: nil
otherButtonTitles: nil];
for (NSString *title in buttons) {
[actionSheet addButtonWithTitle: title];
}
[actionSheet addButtonWithTitle: @"Cancel"];
[actionSheet setCancelButtonIndex: [buttons count]];
[actionSheet showInView:self.view];
}
Вы можете добавить кнопку отмены и установить ее следующим образом:
[actionSheet setCancelButtonIndex: [actionSheet addButtonWithTitle: @"Cancel"]];
Я знаю, что это старый пост, но на случай, если кто-то еще, как и я, пытается в этом разобраться.
(На это ответил @kokemomuke.В основном это более подробное объяснение.Также опираясь на @Ephraim и @Simon)
Оказывается, что Последние запись addButtonWithTitle:должен быть тем Cancel
кнопка.Я бы использовал:
// All titles EXCLUDING Cancel button
for( NSString *title in titles)
[sheet addButtonWithTitle:title];
// The next two line MUST be set correctly:
// 1. Cancel button must be added as the last entry
// 2. Index of the Cancel button must be set to the last entry
[sheet addButtonWithTitle:@"Cancel"];
sheet.cancelButtonIndex = titles.count - 1;