uitableviewcontroller uitableviewcell personalizadas example custom celdas ios uitableview swift

ios - uitableviewcell - uitableview swift 4



UITableViewRowAction título como icono de imagen en lugar de texto (7)

En iOS 11 , Apple proporciona una forma de ayudarnos a hacer eso. Hay dos funciones que necesita implementar para deslizar la celda hacia la izquierda o hacia la derecha

public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

Por ejemplo:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .normal, title: "", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in // Call edit action // Reset state success(true) }) deleteAction.image = UIImage(named: "ic_delete") deleteAction.backgroundColor = .red return UISwipeActionsConfiguration(actions: [deleteAction]) }

Si quieres aplicarlo para iOS <11.0 , puedes hacerlo de una manera complicada

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .default, title: "") { action, indexPath in // Handle delete action } (UIButton.appearance(whenContainedInInstancesOf: [UIView.self])).setImage(UIImage(named: "ic_delete"), for: .normal) return [deleteAction] }

Quiero poner el ícono (imagen) en lugar de texto en acciones de barrido en tableviewCell en Swift.

Pero no sé cómo poner la imagen en lugar del texto del título.

Mi código está abajo:

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in // 2 let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .ActionSheet) let twitterAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: nil) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) shareMenu.addAction(twitterAction) shareMenu.addAction(cancelAction) self.presentViewController(shareMenu, animated: true, completion: nil) }) // 3 var rateAction = (style: UITableViewRowActionStyle.Default, title: "rate",im , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in // 4 let rateMenu = UIAlertController(title: nil, message: "Rate this App", preferredStyle: .ActionSheet) let appRateAction = UIAlertAction(title: "Rate", style: UIAlertActionStyle.Default, handler: nil) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) rateMenu.addAction(appRateAction) rateMenu.addAction(cancelAction) self.presentViewController(rateMenu, animated: true, completion: nil) }) // 5 return [shareAction,rateAction] }

¿Puede alguien ayudarme en esto?

Gracias por adelantado


Estaba buscando hacer lo mismo y encontré una respuesta aquí . Es un poco de una solución.

Además, como se ve en las versiones beta de iOS 9, creo que esto será posible, pero aún no he analizado las API.


Hay dos formas de lograr esto.

  • Use caracteres Unicode en su texto, si le sirve a su propósito, sin embargo, los caracteres Unicode tienen un conjunto limitado.
  • Use emojis siempre que sirvan a su propósito.

Así es como lo haces en el código

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .Default, title: "/u{267A}/n Delete") { action, index in print("more button tapped") self.tableView(tableView, commitEditingStyle: UITableViewCellEditingStyle.Delete, forRowAtIndexPath: indexPath) } delete.backgroundColor = UIColor(rgba: "#ef3340") let apply = UITableViewRowAction(style: .Default, title: "/u{2606}/n Like") { action, index in print("favorite button tapped") self.tableView(tableView, commitEditingStyle: UITableViewCellEditingStyle.Insert, forRowAtIndexPath: indexPath) } apply.backgroundColor = UIColor.orangeColor() let take = UITableViewRowAction(style: .Normal, title: "/u{2605}/n Rate") { action, index in print("share button tapped") self.tableView(tableView, commitEditingStyle: UITableViewCellEditingStyle.None, forRowAtIndexPath: indexPath) } take.backgroundColor = UIColor(rgba: "#00ab84") return [take, apply, delete] }

Esto es lo que podría lograr mediante las formas mencionadas anteriormente:


No Swift, pero para cualquier otra persona que aterrice aquí buscando una solución ... Tengo buenos resultados con la siguiente subclase simple:

@interface GSBTableViewRowAction : UITableViewRowAction @property UIImage *icon; @property UIFont *font; + (instancetype)rowActionWithStyle:(UITableViewRowActionStyle)style title:(NSString *)title icon:(UIImage*)icon handler:(void (^)(UITableViewRowAction *action, NSIndexPath *indexPath))handler; @end @implementation GSBTableViewRowAction + (instancetype)rowActionWithStyle:(UITableViewRowActionStyle)style title:(NSString *)title icon:(UIImage*)icon handler:(void (^)(UITableViewRowAction *action, NSIndexPath *indexPath))handler { if (title.length) title = [@"/n" stringByAppendingString:title]; // move title under centerline; icon will go above GSBTableViewRowAction *action = [super rowActionWithStyle:style title:title handler:handler]; action.icon = icon; return action; } - (void)_setButton:(UIButton*)button { if (self.font) button.titleLabel.font = self.font; if (self.icon) { [button setImage:[self.icon imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal]; button.tintColor = button.titleLabel.textColor; CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:button.titleLabel.font}]; button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height/2 + 5), 0, 0, -titleSize.width); // +5px gap under icon }

El rowActionWithStyle:title:icon:handler es realmente solo un método conveniente: la ''salsa secreta'' está anulando el método (privado?) _setButton [crédito a Jayesh por esto!].

Esto le dará un ícono centrado sobre el título, o solo el icono solo si deja el título nulo. Desafortunadamente, no puedes jugar con la posición del título usando button.titleEdgeInsets , como puedes imageEdgeInsets , así que lo mejor que puedo hacer es poner el título inmediatamente debajo de la línea central (de ahí el ''/ n'') con un pequeño espacio debajo del ícono ( 5px arriba). Los resultados se ven como

Como beneficio adicional, también puede cambiar la fuente del título, para decir algo más pequeño, configurando la nueva propiedad de la font . por ejemplo, la acción ''Agregar'' anterior se realizó con

GSBTableViewRowAction *add = [GSBTableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Add" icon:[UIImage imageNamed:@"Today-25"] handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){ [self addToCalendar:self]; [tableView setEditing:NO animated:YES]; }]; add.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]; add.backgroundColor = UIColor.orangeColor;

Advertencia: _setButton es API privada, por lo que YMMV ... Todos esperamos que Apple exponga una API pública para hacer lo que aparentemente hacen en su Mail.app [sic]


Prueba esto

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let remove = UITableViewRowAction(style: .Default, title: " ") { action, indexPath in print("delete button tapped") } remove.backgroundColor = UIColor(patternImage: UIImage(named: "Delete")!) return [remove] }



trailingSwipeActionsConfigurationForRowAtIndexPath funciona solo desde iOS 11 y no se puede personalizar por completo. Puede cambiar el color de fondo de un botón, pero no puede agregar una imagen con sus propios colores, incluso si usa UIImageRenderingModeAlwaysOriginal .

Terminé usando MGSwipeTableCell .