Could you tell me, how to add custom image to delete button when swipe cell on UITableview?
100 % working Swipable cell with custom image and size of image with background color ios swift #ios #swift #ios13 #ios14
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(style: .normal, title: "", handler: { (action,view,completionHandler ) in
self.selectedIndex = indexPath.row
self.deleteNotification()
completionHandler(true)
})
if #available(iOS 13.0, *) {
action.image = UIGraphicsImageRenderer(size: CGSize(width: 30, height: 30)).image { _ in
UIImage(named: "delete-1")?.draw(in: CGRect(x: 0, y: 0, width: 30, height: 30))
}
action.backgroundColor = UIColor.init(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.0)
let confrigation = UISwipeActionsConfiguration(actions: [action])
return confrigation
} else {
// Fallback on earlier versions
let cgImageX = UIImage(named: "delete-1")?.cgImage
action.image = OriginalImageRender(cgImage: cgImageX!)
action.backgroundColor = UIColor.init(hex: "F7F7F7")
let confrigation = UISwipeActionsConfiguration(actions: [action])
return confrigation
}
}
There's this UITableView delegate function you can make use of:
@available(iOS 11.0, *)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .normal, title: "", handler: {a,b,c in
// example of your delete function
self.YourArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
})
deleteAction.image = UIImage(named: "trash.png")
deleteAction.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [deleteAction])
}
PS: Personally, I think icon size 32 is the best
search you need function "editActionsForRowAtIndexPath", where you create scope of actions. You need to set UIImage to backgroundColor of UITableViewRowAction.
let someAction = UITableViewRowAction(style: .Default, title: "") { value in
println("button did tapped!")
}
someAction.backgroundColor = UIColor(patternImage: UIImage(named: "myImage")!)