Заголовок UITableViewRowAction как значок изображения вместо текста
Я хочу поместить значок (изображение) вместо текста в действия салфетки в tableviewCell в Swift.
Но я не помещаю изображение вместо текста заголовка?
Мой код ниже:
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]
}
Можете ли вы кому-нибудь помочь мне в этом?
Заранее спасибо
Ответы
Ответ 1
Есть два способа добиться этого.
- Используйте символы Unicode в тексте, если он служит вашей цели. Однако символы Unicode ограничены.
- Используйте emojis при условии, что он служит вашей цели.
Вот как вы это делаете в коде
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]
}
Это то, что я мог бы достичь вышеупомянутыми способами -
![введите описание изображения здесь]()
Ответ 2
В iOS 11 Apple предоставляет нам способ помочь нам в этом.
Есть две функции, которые вам нужно реализовать для прокрутки ячейки влево или вправо.
public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
public func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
Например:
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])
}
Если вы хотите применить его для iOS < 11.0, вы можете сделать это с помощью сложного пути
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]
}
Ответ 3
Not Swift, но для любого, кто приземляется здесь, ищет решение... У меня хорошие результаты со следующим простым подклассом:
@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
}
rowActionWithStyle:title:icon:handler
на самом деле просто метод удобства - "секретный соус" переопределяет (частный?) метод _setButton [кредит для Jayesh для этого!].
Это даст вам значок с центром по названию или только значок в одиночку, если вы оставите нулевой заголовок. К сожалению, вы не можете поиграть с позицией заголовка, используя button.titleEdgeInsets
, как вы можете imageEdgeInsets
, поэтому я могу лучше всего поместить заголовок под осевой линией (отсюда "\n" ) с небольшим промежутком под значок (5px выше). Результаты выглядят как
![действие строки с заголовком + значок]()
В качестве бонуса вы также можете изменить шрифт заголовка, чтобы сказать что-то меньшее, установив новое свойство font
. например, вышеупомянутое действие "Добавить" было выполнено с помощью
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;
Предостережение: _setButton - частный API, поэтому YMMV... Мы все надеемся, что Apple опубликует открытый API, чтобы делать то, что они apparantly делают в своем Mail.app [sic]
Ответ 4
Попробуйте это
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]
}
![введите описание изображения здесь]()
Ответ 5
Я искал сделать то же самое и нашел ответ здесь. Это немного обходное решение.
Кроме того, как видно из бета-версии iOS 9, я думаю, что это будет возможно, но я еще не посмотрел API.
Ответ 6
trailingSwipeActionsConfigurationForRowAtIndexPath
работает только с iOS 11 и полностью не настраивается. Вы можете изменить цвет фона кнопки, но вы не можете добавить изображение с вашими собственными цветами, даже если вы используете UIImageRenderingModeAlwaysOriginal
.
В итоге я использовал MGSwipeTableCell
.
Ответ 7
Если вы используете ответ "Apps Wise" (fooobar.com/info/93295/...), вы можете использовать эту таблицу для общих символов Unicode:
https://tutorialzine.com/2014/12/you-dont-need-icons-here-are-100-unicode-symbols-that-you-can-use
Или этот для ВСЕХ символов Юникода:
https://unicode-table.com/en/#control-character