mpc75
mpc75

Reputation: 989

How do I change the color of an SF Symbols icon in Swift?

I realize this question has been asked here twice but none of the solutions provided are working for me. My icon is showing up but it is showing with a blue outline rather than the red I have requested. Swift is telling me that setting the foreground color is not an option

let largeConfig = UIImage.SymbolConfiguration(pointSize: heartPointSize)

let emptyHeartIcon = UIImage(systemName: "heart", withConfiguration:largeConfig)?.withTintColor(.systemRed) // this did not work

emptyHeartIcon?.withTintColor(.systemRed) // this also did not work
emptyHeartIcon!.withTintColor(.systemRed) // thought maybe it was because I wasn't unwrapping it but this also didn't work

If you're so inclined here's the context of the symbol :)

func levelUpsShown(){

    let levelUpShownStackView = UIStackView(arrangedSubviews: [])
    levelUpShownStackView.frame = CGRect(x: 15, y: 15, width: levelUpsShownView.bounds.width - 30, height: levelUpsShownView.bounds.height - 30)

    let heartPointSize = (levelUpsShownView.bounds.width - 30)/8
    let heartLocation = (levelUpsShownView.bounds.width - 38)/12

    (0..<6).forEach { (levelUpsBucket) in
        let largeConfig = UIImage.SymbolConfiguration(pointSize: heartPointSize)
        let emptyHeartIcon = UIImage(systemName: "heart", withConfiguration: largeConfig)
        let emptyHeartView = UIImageView(image: emptyHeartIcon)

        let levelUpSegment = UIView()
        levelUpSegment.addSubview(emptyHeartView)

        emptyHeartView.center = CGPoint(x: heartLocation, y: 40)

        levelUpShownStackView.addArrangedSubview(levelUpSegment)
    }
    levelUpShownStackView.distribution = .fillEqually
    levelUpShownStackView.spacing = 4
    levelUpsShownView.addSubview(levelUpShownStackView)
}

Upvotes: 1

Views: 2260

Answers (1)

Morgan Le Gal
Morgan Le Gal

Reputation: 116

Try to change the tint of the UIImageView instead of the UIImage.

emptyHeartView.tintColor = .systemRed

If you don't want an UIImageView, check this post; https://stackoverflow.com/a/19152722/8258494

Basically applying a mask on your image.

Upvotes: 4

Related Questions