How to change the color of a UIImage in Swift

iOS 13 and above (Swift 5.1):

Declaration (see Docs)

func withTintColor(_ color: UIColor) -> UIImage

usage:

yourUIImage.withTintColor(color: UIColor)

If you use PNG images (as i think because of icons) - just use:

let originalImage = UIImage(named: "iconName")
let tintedImage = originalImage?.withRenderingMode(.alwaysTemplate)
yourButton.setImage(tintedImage, forState: .normal)
yourButton.tintColor = UIColor.blue //change color of icon

edit/update:

For iOS10+ we can use UIGraphicsImageRenderer:

Xcode 11 • Swift 5.1

extension UIImage {
    func tinted(with color: UIColor, isOpaque: Bool = false) -> UIImage? {
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: size, format: format).image { _ in
            color.set()
            withRenderingMode(.alwaysTemplate).draw(at: .zero) 
        }
    }
}

Playground Testing

let camera = UIImage(data: try! Data(contentsOf: URL(string: "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-camera-128.png")!))!
let redCamera = camera.tinted(with: .red)

original answer

You can use UIGraphicsBeginImageContextWithOptions to begin an image context, set the desired color and use image's method func draw(in rect: CGRect) to draw your icon image using rendering mode .alwaysTemplate on it:

extension UIImage {
    func tinted(with color: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }
        color.set()
        withRenderingMode(.alwaysTemplate)
            .draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

enter image description here