Search code examples
uitableviewswift3uiimage

Stop repeating UIImage background pattern image - Swift


I'm using swipe to delete in UITableView. In swipe I need to add image. When I add image it repeats. How to stop repeating

 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let deleteButton = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in
            self.tableView.dataSource?.tableView!(self.tableView, commit: .delete, forRowAt: indexPath)
            return
        }

        deleteButton.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "favourite_delete"))
        deleteButton.title = ""
            return [deleteButton]
}

Problem

enter image description here

What I need

enter image description here


Solution

  • The problem, as you might have guessed, is here:

    deleteButton.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "favourite_delete"))
    

    You are creating a UIColor using the (patternImage:) initializer. This means that the image will be repeated (See the word "pattern"?).

    From the docs:

    You can use pattern colors to set the fill or stroke color just as you would a solid color. During drawing, the image in the pattern color is tiled as necessary to cover the given area.

    To solve this, you can resize your image so that it fits the frame of the button programmatically. See The simplest way to resize an UIImage?

    Alternatively, use MGSwipeTableViewCell, it allows you to put images on swipe buttons.