TayaR
TayaR

Reputation: 31

Changing tint color of system image in trailing swipe action

I'm trying to change color of trash system image but it doesn't work for some reason.

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .normal, title: nil) { (ac: UIContextualAction, view: UIView, success: (Bool) -> Void) in
        let cell = tableView.cellForRow(at: indexPath) as? HeroTableViewCell
        if let _ = cell?.nameLabel.text {
            self.deleteHeroName(index: indexPath)
        }
        success(true)
    }
    deleteAction.image = UIImage(systemName: "trash")?.withTintColor(.red)
    return UISwipeActionsConfiguration(actions: [deleteAction])
}

I need it because I'm trying to give clear background to my delete action and image color is white.

Upvotes: 1

Views: 794

Answers (2)

ItsTim
ItsTim

Reputation: 11

    // Updated the image rendering to `.alwaysTemplate` and applied a tint color to ensure the icon color can be customized.
    // This change was necessary because `UIContextualAction` often ignores custom tint colors unless the image is rendered as a template.
    if let deleteBinImage = UIImage(systemName: "trash")?.withRenderingMode(.alwaysTemplate){
        let tintedImage = deleteBinImage.withTintColor(.red, renderingMode: .alwaysOriginal)
        deleteAction.image = tintedImage
    }

Upvotes: 1

zalogatomek
zalogatomek

Reputation: 746

For me adding rendering mode as .alwaysOriginal (note, not .alwaysTemplate as we would usually use for tinting an image) worked:

action.image = UIImage(systemName: "trash")?.withTintColor(.red, renderingMode: .alwaysOriginal)

Upvotes: 2

Related Questions