Use NSArray para especificar otherButtonTitles?
-
05-07-2019 - |
Pregunta
El constructor UIAlertSheet toma un parámetro otherButtonTitles como una lista varg. Me gustaría especificar los otros títulos de botones de una NSArray en su lugar. ¿Es esto posible?
es decir, Tengo que hacer esto:
id alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: button1Title, button2Title, nil];
Pero como estoy generando la lista de botones disponibles en tiempo de ejecución, realmente quiero algo como esto:
id alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: otherButtonTitles];
Ahora mismo, estoy pensando que necesito tener una llamada separada a initWithTitle:
para 1 elemento, 2 elementos y 3 elementos. Así:
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
}
Eso es mucho código duplicado, pero en realidad podría ser razonable, ya que tengo como máximo tres botones. ¿Cómo puedo evitar esto?
Solución
Este es un año de antigüedad pero la solución es bastante simple ... haga lo que sugiere @Simon pero no especifique el título del botón de cancelación, así que:
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: nil
destructiveButtonTitle: nil
otherButtonTitles: nil];
Pero después de agregar sus botones normales, agregue el botón de cancelar, como:
for( NSString *title in titles) {
[alert addButtonWithTitle:title];
}
[alert addButtonWithTitle:cancelString];
Ahora, el paso clave es especificar qué botón es el botón de cancelación, como:
alert.cancelButtonIndex = [titles count];
Hacemos [conteo de títulos]
y no [conteo de títulos] - 1
porque estamos agregando el botón de cancelación como extra de la lista de botones en los títulos de
.
Ahora también especifica qué botón desea que sea el botón destructivo (es decir, el botón rojo) especificando el índice de botón destructivo (normalmente ese será el botón [conteo de títulos] - 1
). Además, si mantienes el botón Cancelar para ser el último botón, iOS agregará ese espacio agradable entre los otros botones y el botón Cancelar.
Todos estos son compatibles con iOS 2.0, así que disfruta.
Otros consejos
En lugar de agregar los botones al inicializar UIActionSheet, intente agregarlos con el método addButtonWithTitle usando un bucle for que pasa por su NSArray.
UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle: titleString
delegate: self
cancelButtonTitle: cancelString
destructiveButtonTitle: nil
otherButtonTitles: nil];
for( NSString *title in titles)
[alert addButtonWithTitle:title];
addButtonWithTitle: devuelve el índice del botón agregado. Establezca cancelButtonTitle en nil en el método init y, después de agregar botones adicionales, ejecute esto:
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];
}
Puedes agregar el botón de cancelación y configurarlo de esta manera:
[actionSheet setCancelButtonIndex: [actionSheet addButtonWithTitle: @"Cancel"]];
Sé que esta es una publicación antigua, pero en caso de que alguien más, como yo, esté tratando de resolver esto.
(Esto fue respondido por @kokemomuke. Esto es principalmente una explicación más detallada. También se basa en @Ephraim y @Simon)
Resulta que la entrada ÚLTIMA de addButtonWithTitle: debe ser el botón Cancelar
. Yo usaría:
// 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;