Set Gradient Tint Color for Segmented Control iOS Swift 4
As developers, we use a great color combination to produce a good-looking result when creating an app, to achieve the best user experience ...
https://bethedev.blogspot.com/2019/02/set-gradient-tint-color-for-segmented.html
As developers, we use a great color combination to produce a good-looking result when creating an app, to achieve the best user experience possible. Simple colors might not be good enough for some certain outcomes in certain UI. but gradient could become best to fit UI.
Here I have provided a guide for customizing
If this code was helpful, I would love to hear from you or If you have any questions please post your comments below.
Thank you!
UISegmentedControl
with gradient colors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IBOutlet weak var segmentView: UISegmentedControl!{ | |
didSet{ | |
self.updateGradientBackground() | |
self.segmentView.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white],for: UIControl.State.normal) | |
self.segmentView.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.white],for: UIControl.State.selected) | |
} | |
} | |
fileprivate func updateGradientBackground() { | |
let sortedViews = segmentView.subviews.sorted( by: { $0.frame.origin.x < $1.frame.origin.x } ) | |
for (_, view) in sortedViews.enumerated() { | |
let gradientImage = gradient(size: segmentView.frame.size, color: [UIColor.cyan,UIColor.blue])! | |
view.backgroundColor = UIColor(patternImage: gradientImage) | |
view.tintColor = UIColor.clear | |
} | |
} | |
func gradient(size:CGSize,color:[UIColor]) -> UIImage?{ | |
//turn color into cgcolor | |
let colors = color.map{ $0.cgColor} | |
//begin graphics context | |
UIGraphicsBeginImageContextWithOptions(size, true, 0.0) | |
guard let context = UIGraphicsGetCurrentContext() else { | |
return nil | |
} | |
// From now on, the context gets ended if any return happens | |
defer {UIGraphicsEndImageContext()} | |
//create core graphics context | |
let locations:[CGFloat] = [0.0,1.0] | |
guard let gredient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as NSArray as CFArray, locations: locations) else { | |
return nil | |
} | |
//draw the gradient | |
context.drawLinearGradient(gredient, start: CGPoint(x:0.0,y:size.height), end: CGPoint(x:size.width,y:size.height), options: []) | |
// Generate the image (the defer takes care of closing the context) | |
return UIGraphicsGetImageFromCurrentImageContext() | |
} | |
If this code was helpful, I would love to hear from you or If you have any questions please post your comments below.
Thank you!