1

Is there a way to make progressTintColor make a gradient one? Specifically I would like to make it a gradient color from green to red - standard temperature mode.

Adding sublayer didn't work as it put the layer "behind" the view:

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.testBar.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor greenColor] CGColor], (id)[[UIColor redColor] CGColor], nil];
[self.testBar.layer insertSublayer:gradient atIndex:0];
Michal
  • 15,429
  • 10
  • 73
  • 104

2 Answers2

2

You could try creating patterned UIColor and set that as the tint color, but I doubt it would work.

Otherwise you will probably need to subclass UIProgressView or build your own UIView subclass. A progress bar isn't that difficult to draw.

Community
  • 1
  • 1
Rengers
  • 14,911
  • 1
  • 36
  • 54
0

I found this and it works very well in my local

https://medium.com/academy-poa/how-to-create-a-uiprogressview-with-gradient-progress-in-swift-2d1fa7d26f24

1.Extent UIImage

    extension UIImage {
    
        public convenience init?(bounds: CGRect, colors: [UIColor], orientation: GradientOrientation = .horizontal) {
            let gradientLayer = CAGradientLayer()
            gradientLayer.frame = bounds
            gradientLayer.colors = colors.map({ $0.cgColor })
            
            if orientation == .horizontal {
                gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5);
                gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5);
            }
            
            UIGraphicsBeginImageContext(gradientLayer.bounds.size)
            gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            guard let cgImage = image?.cgImage else { return nil }
            self.init(cgImage: cgImage)
        }
    }

public enum GradientOrientation {
    case vertical
    case horizontal
}
  1. create your own gradient progress bar

import UIKit

class GradientProgressView: UIProgressView {
    
@IBInspectable var firstColor: UIColor = UIColor.white {
    didSet {
        updateView()
    }
}

@IBInspectable var secondColor: UIColor = UIColor.black {
    didSet {
        updateView()
    }
}

func updateView() {
            
    if let gradientImage = UIImage(bounds: self.bounds, colors: [firstColor, secondColor]) {
        self.progressImage = gradientImage
    }
}

}

  1. in your class

    let progressView = GradientProgressView(progressViewStyle: .bar)

     progressView.firstColor = UIColor(red: 0.949, green: 0.478, blue: 0.329, alpha: 1) //your own color
     progressView.secondColor = UIColor(red: 0.631, green: 0.329, blue: 0.949, alpha: 1) //your own color
     progressView.updateView()
    
Energy
  • 940
  • 13
  • 20