iphone objective-c uiimage uiactionsheet uidocumentinteraction

iphone - Agregar imágenes a los botones UIActionSheet como en UIDocumentInteractionController



objective-c uiimage (12)

¿Es posible agregar una imagen a los botones de UIActionSheet como se ve en UIDocumentInteractionController ? Si es así, hágamelo saber cómo se hace.


Acabo de crear una clase que emula el aspecto de una UIActionSheet utilizando celdas de tabla que admiten imágenes y texto para cada fila. También usa bloques para la interacción, admite iPhone y iPad, ventana emergente de un UITabBarItem en iPad y cola de múltiples hojas. Todavía está en desarrollo, pero puede clonarlo desde Github:

http://github.com/azplanlos/SIActionSheet

El uso es bastante simple, aquí hay un ejemplo:

SIActionSheet* mySheet = [SIActionSheet actionSheetWithTitle:@"Action Sheet title" andObjects:[NSArray arrayWithObjects: [SIActionElement actionWithTitle:@"Item 1" image:[UIImage imageNamed:@"image"] andAction:^{NSLog(@"action 1");}] , nil] completition:^(int num) { NSLog(@"pressed %i", num); } cancel:^{NSLog(@"canceled");}]; mySheet.followUpSheet = anotherSheet; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) [mySheet show]; else [mySheet showFromTabBarItem:item inTabBar:tabBar];

Si encuentra algún problema, hágamelo saber. Espero que esto ayude a mucha gente a tener el mismo problema que yo ...



Desde iOS 8.0 puedes usar UIAlertController. En UIAlertController, cada elemento del botón se conoce como UIAlertAction, que se agrega en consecuencia.

Puedes verificar mi respuesta


Encontré que esta extensión de categoría funciona en ios7.1 para agregar una imagen / icono a los botones en una Hoja UIAction, con algunas advertencias ...

@interface UIActionSheet (GSBActionSheetButtons) - (void)buttonAtIndex:(NSUInteger)index setImage:(UIImage *)image forState:(UIControlState)state; @end @implementation UIActionSheet (GSBActionSheetButtons) - (void)buttonAtIndex:(NSUInteger)index setImage:(UIImage *)image forState:(UIControlState)state { for (UIView* view in self.subviews) { if ([view isKindOfClass:[UIButton class]]) { if (index-- == 0) { UIButton *button = (UIButton*)view; [button setImage:image forState:state]; button.imageView.contentMode = UIViewContentModeScaleAspectFit; button.imageEdgeInsets = UIEdgeInsetsMake(2,0,2,0); break; } } } }

Y para usarlo:

[self.sharePopup buttonAtIndex:2 setImage:[UIImage imageNamed:@"twitter.png"] forState:UIControlStateNormal];

Las advertencias:

  • Aunque UIActionSheet realiza correctamente el autosize de su imagen a la altura correcta para el botón, no parece que cambie el ancho de la imagen ; de ahí la necesidad de UIViewContentModeScaleAspectFit para evitar que la imagen quede aplastada. Sin embargo, el ancho del marco de la vista de imagen sigue siendo el tamaño completo original, por lo que si su imagen era grande (o más ancha), entonces obtendrá una brecha molesta entre la imagen centrada (encogida) y el texto del botón. No he encontrado forma de evitar esto; incluso al agregar programáticamente una anchura explícita = restricción de altura a la imagen, parece que se ignora. [¿algunas ideas?]. Resultado neto, asegúrese de que su imagen tenga aproximadamente la altura correcta para comenzar (por ejemplo, alrededor de 45 píxeles en un iPhone 4S) o obtendrá un espacio cada vez más grande entre la imagen del botón y el texto.

  • Más grave, tan pronto como agrega una imagen al botón, UIActionSheet parece hacer que el texto del botón se ponga en negrita automáticamente (!). No sé por qué y no sé cómo prevenir esto [¿alguna idea?]

  • Por último, esta solución se basa en que las subvistas de UIActionSheet están en el mismo orden en que se indexan los botones. Esto es cierto para un puñado de botones, pero (al parecer) cuando tienes muchos elementos en tu UIActionSheet, Apple tiene problemas con la indexación [pero tendrás problemas con esto de todos modos en actionSheet: clickedButtonAtIndex: cuando tratas de averiguar qué botón se pulsó ...]

Oh, imageEdgeInsets: es opcional: inserto cada imagen un par de píxeles dentro del botón para que las imágenes no se toquen verticalmente.

[Opinión: dadas las rarezas anteriores, me da la sensación de que Apple realmente no quiere que la gente se cague con sus hojas de acción. En algún momento, probablemente tendrá que morder y simplemente implementar su propia ventana emergente modal; solo hay un mal manejo de estas UIActionSheets acomodadas ...]


Existe la posibilidad de agregar imágenes (para ser exactos: íconos o símbolos) a los botones de una UIActionSheet (o una UIAlertView ) sin cargar archivos de imágenes o juguetear con (sub) vistas. En estas clases, los botones se especifican por sus títulos, que son cadenas. Entonces, es obvio usar símbolos, que uno puede especificar también por cadenas. Lo primero que se me ocurrió fue usar símbolos unicode .

Luego descubrí que varios de ellos se muestran como iconos bonitos en iOS y también se pueden ver varios símbolos en el Visor de caracteres en Mac OS. Por lo tanto, los símbolos se pueden usar en cualquier lugar donde se pueda especificar una cadena.

Los inconvenientes de este enfoque son:

  • Usted está limitado a símbolos predefinidos.
  • No todos los símbolos se representan como deberían (por ejemplo, /u29C9 ).
  • Puede haber cambios en la apariencia de algunos símbolos en diferentes versiones de iOS (por ejemplo, /U0001F533 en iOS 5 y 6).

Aquí hay algunos símbolos interesantes, entre otros:

Si desea comprobar rápidamente cómo se ve un símbolo (al menos en Mac OS), puede usar la Calculadora . Verifique definitivamente en el simulador: por ejemplo, /u2B1C no es un ícono en la Calculadora 10.7.1.

Capturas de pantalla:

UIActionSheet

Títulos de botones:

@"/U0001F6A9 /U0001F4CC /u26F3 /u2690 /u2691 /u274F /u25A4 Test" @"/U0001F4D6 /U0001F30E /U0001F30F /u25A6 /U0001F3C1 /U0001F332 /U0001F333 /U0001F334 Test"

UIAlertView

Título del botón:

@"/u26A0 Yes"

UITableViewCell con casilla de verificación y otros iconos


Intenta de esta manera, espero que pueda ser de ayuda.

UIActionSheet * action = [[UIActionSheet alloc] initWithTitle:@"Title" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"",nil]; [[[action valueForKey:@"_buttons"] objectAtIndex:0] setImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal]; [[[action valueForKey:@"_buttons"] objectAtIndex:0] setImage:[UIImage imageNamed:@"yourImage_Highlighted.png"] forState:UIControlStateHighlighted];


La UIActionSheet estándar no admite imágenes.

Una forma de agregar una imagen a UIActionSheet es agregar una subvista a UIActionSheet . Simplemente implemente el método UIActionSheetDelegate willPresentActionSheet: así:

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet { UIImageView* buttonImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picturename.png"]]; // Set the frame of the ImageView that it''s over the button. [actionSheet addSubview:buttonImage]; [buttonImage release]; // only if you don''t need this anymore }

No estoy seguro de si la imagen responde a los toques, pero puede construir una UIActionSheet como UIDocumentInteractionController .


Para iOS 8, haz referencia a esto

if( [UIAlertController class] ){ UIAlertController *view = [UIAlertController alertControllerWithTitle:@"Main Title" message:@"What do you want to do?" preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *firstAA = [UIAlertAction actionWithTitle:@"Beep Beep" style:UIAlertActionStyleDefault handler:^( UIAlertAction *action ){ [view dismissViewControllerAnimated:YES completion:nil]; }]; [firstAA setValue:[UIImage imageNamed:@"your-icon-name"] forKey:@"image"]; [view addAction:firstAA]; UIAlertAction *cancelAA = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^( UIAlertAction *action ){ [self deselectTableViewRow]; [view dismissViewControllerAnimated:YES completion:nil]; }]; [view addAction:cancelAA]; [self presentViewController:view animated:YES completion:nil]; } else { UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"What do you want to do?" delegate:(id)self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [sheet addButtonWithTitle:@"title"]; [[[sheet valueForKey:@"_buttons"] objectAtIndex:0] setImage:[UIImage imageNamed:@"your-icon-name.png"] forState:UIControlStateNormal]; sheet.cancelButtonIndex = [sheet addButtonWithTitle:@"Cancel"]; [sheet showInView:self.view]; }


Puede obtener el título del botón de acción del objeto actionSheet con la tecla " _buttons " y establecer la imagen del botón.

UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"Title" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook", @"Twitter", @"Google +", @"E - mail", @"Send Message",nil]; [[[actionSheet valueForKey:@"_buttons"] objectAtIndex:0] setImage:[UIImage imageNamed:@"fb_icon1.png"] forState:UIControlStateNormal]; [[[actionSheet valueForKey:@"_buttons"] objectAtIndex:1] setImage:[UIImage imageNamed:@"tweet_icon1.png"] forState:UIControlStateNormal]; [[[actionSheet valueForKey:@"_buttons"] objectAtIndex:2] setImage:[UIImage imageNamed:@"googleplus_icon1.png"] forState:UIControlStateNormal]; [[[actionSheet valueForKey:@"_buttons"] objectAtIndex:3] setImage:[UIImage imageNamed:@"mail_icon.png"] forState:UIControlStateNormal]; [[[actionSheet valueForKey:@"_buttons"] objectAtIndex:4] setImage:[UIImage imageNamed:@"message_icon.png"] forState:UIControlStateNormal]; for (UIView *subview in actionSheet.subviews) { if ([subview isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)subview; [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; } } [actionSheet showInView:self.view];


Sé que es una respuesta tardía, pero encontré otra forma de mostrar la imagen en la hoja de acción:

self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Image:" delegate:self cancelButtonTitle:@"Cancel"destructiveButtonTitle:nil otherButtonTitles: @"Image1", @"Image2", @"Image3", @"Image4", @"Image5", @"Image6", @"Image7", @"Image8",@"Image9", @"Image10", @"Image11", @"Image12", @"Image13", @"Image14", @"Image15", nil]; self.actionSheet.tag = 1; for (id button in [self.actionSheet valueForKey:@"_buttons"]) { UIImageView* buttonImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[button titleForState:UIControlStateNormal]]]; [buttonImage setFrame:CGRectMake(5, 5,35,35)]; [button addSubview:buttonImage]; } [self.actionSheet showInView:[UIApplication sharedApplication].keyWindow];


NSString* strUrl=[MLControl shared].currentServerUrl; for( MLServerUrl *title in [MLControl shared].arrServerUrl) { NSString* strShow=title.name; if ([strUrl isEqualToString: title.url]) { strShow=[NSString stringWithFormat:@"√ %@",strShow]; }else{ strShow=[NSString stringWithFormat:@" %@",strShow]; } [chooseImageSheet addButtonWithTitle:strShow]; } // [[[chooseImageSheet valueForKey:@"_buttons"] objectAtIndex:0] setImage:[UIImage imageNamed:@"ic_check_black_18dp.png"] forState:UIControlStateNormal]; chooseImageSheet.actionSheetStyle = UIActionSheetStyleDefault; [chooseImageSheet showFromRect:btnRc inView:sender animated:YES];


- (IBAction)actionSheetButtonPressed:(id)sender { UIAlertController * view= [UIAlertController alertControllerWithTitle:@"Share " message:@"Select your current status" preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction* online = [UIAlertAction actionWithTitle:@"Facebook" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { //Do some thing here [view dismissViewControllerAnimated:YES completion:nil]; }]; UIAlertAction* offline = [UIAlertAction actionWithTitle:@"Google+" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { [view dismissViewControllerAnimated:YES completion:nil]; }]; UIAlertAction* doNotDistrbe = [UIAlertAction actionWithTitle:@"LinkedIn" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { [view dismissViewControllerAnimated:YES completion:nil]; }]; UIAlertAction* away = [UIAlertAction actionWithTitle:@"Twitter" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) { [view dismissViewControllerAnimated:YES completion:nil]; }]; UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { }]; [online setValue:[[UIImage imageNamed:@"facebook.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; [offline setValue:[[UIImage imageNamed:@"google-plus.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; [doNotDistrbe setValue:[[UIImage imageNamed:@"linkedin.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; [away setValue:[[UIImage imageNamed:@"twitter.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; [view addAction:online]; [view addAction:away]; [view addAction:offline]; [view addAction:doNotDistrbe]; [view addAction:cancel]; [self presentViewController:view animated:YES completion:nil];

}