UITableViewRowAction title as image icon instead of text

前端 未结 8 1977
谎友^
谎友^ 2020-12-07 22:53

I want put the icon (image) instead of text in swipe actions in tableviewCell in Swift.

But i dont how to put the image instead of title text?

My code is be

8条回答
  •  悲哀的现实
    2020-12-07 23:23

    In iOS 11, Apple provides a way to help us do that. There are 2 functions you need to implement to swipe cell to left or right

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

    For example:

    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])
        }
    

    If you want to apply it for iOS < 11.0, you can do it by a tricky way

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

提交回复
热议问题