Henrique Dourado
Henrique Dourado

Reputation: 320

How can I put an image on top of a UITableViewRowAction title?

I've already searched this question but what I found was:

  1. How to put the image as the row action background.

  2. How to put an unicode character \u{unicode here}. It worked, but I couldn't find an unicode character to represent an add button, or a delete button perhaps.

But what I want is to put a custom image on top of the row action title. For example: a trash can with the title delete below it.

I've tried this code too:

"\(UIImage(named: "trashImg"))"

In the row action title string, but xcode didn't seem to count the last ) as part of the code, but only as part of the string. But anyway, I built the project and when I tested, instead of the title, there was a huge text saying some stuff like "optional: (64,)...." etc, it didn't crash tho.

Please help me, many apps do this and I want it on mine too!

Thanks in advance.

Upvotes: 3

Views: 2537

Answers (2)

Anit Kumar
Anit Kumar

Reputation: 8153

You need to change insets according to your requirements.

class TableViewRowAction: UITableViewRowAction 
{
    var image: UIImage?

    func _setButton(button: UIButton)  {

        if let image = image, let titleLabel = button.titleLabel {

             let labelString = NSString(string: titleLabel.text!)
             let titleSize = labelString.sizeWithAttributes([NSFontAttributeName: titleLabel.font])
             button.tintColor = UIColor.whiteColor()
             button.setImage(image.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
             button.imageEdgeInsets.right = -titleSize.width
        }
    }
}


func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {


    let moreRowAction = TableViewRowAction(style: UITableViewRowActionStyle.Default, title: "        ") { action, indexPath in
        // Action Block of more button.
    }

    moreRowAction.image = UIImage(named: "edit_white")
    moreRowAction.backgroundColor = UIColor(red: 252/255, green: 65/255, blue: 75/255, alpha: 1.0)



    let deleteRowAction = TableViewRowAction(style: UITableViewRowActionStyle.Default, title: "        ") { action, indexPath in
          // Action Block of delete button.

    }

    deleteRowAction.backgroundColor = UIColor(red: 252/255, green: 65/255, blue: 75/255, alpha: 1.0)
    deleteRowAction.image = UIImage(named: "delete_white")

    return [deleteRowAction, moreRowAction]

}

Upvotes: 2

hawkstrider
hawkstrider

Reputation: 4341

You are putting the image into a string object which will get the default string representation of that image.

Perhaps this post may help. Looks like they are overriding editActionsForRowAtIndexPath and setting the background color with a patternimage. Custom table view row action (image)

Another post saying basically the same thing UITableViewRowAction image for title

Upvotes: 0

Related Questions