Подтвердить что ты не робот

Использовать NSArray для указания otherButtonTitles?

Конструктор 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
}

Это много дублирующихся кодов, но это может быть разумно, так как у меня есть не более трех кнопок. Как я могу избежать этого?

4b9b3361

Ответ 1

Это год, но решение довольно просто... сделайте так, как предлагал @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, поэтому наслаждайтесь.

Ответ 2

Вместо добавления кнопок при инициализации 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]; 

Ответ 3

addButtonWithTitle: возвращает индекс добавленной кнопки. Установите для параметра cancelButtonTitle значение nil в методе init и после добавления дополнительных кнопок выполните следующее:

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

Ответ 4

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

Ответ 5

Вы можете добавить кнопку отмены и установить ее так:

[actionSheet setCancelButtonIndex: [actionSheet addButtonWithTitle: @"Cancel"]];

Ответ 6

Я знаю, что это старый пост, но если кто-то, как и я, пытается понять это.

(Это было вызвано @kokemomuke. Это в основном более подробное объяснение. Также, основываясь на @Ephraim и @Simon)

Оказывается, LAST запись 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;