How to set UISegmentedControl Tint Color for individual segment
This will solve your problem:
var subViewOfSegment: UIView = mySegmentedControl.subviews[0] as UIView
subViewOfSegment.tintColor = UIColor.blueColor()
You can also
(mySegmentedControl.subviews[0] as UIView).tintColor = UIColor .blueColor()
The easiest way I have found is:
segmentControl.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState: UIControlState.Selected)
This code works fine with latest version of Swift as on August 2019 (Swift 3.0)
Here this code I have implemented is the extension for the Segment control and can be used for all the segment controls in the application, where the set of code has to defined in application class.
Extension method can be used directly in the application, also you can add all the settings to same method or different methods in extension class, as shown below.
extension UISegmentedControl {
func setSegmentStyle() {
setBackgroundImage(imageWithColor(color: backgroundColor!), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
let segAttributes: NSDictionary = [
NSForegroundColorAttributeName: UIColor.gray,
NSFontAttributeName: UIFont(name: "System-System", size: 14)!
]
setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.selected)
}
// create a 1x1 image with this color
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor);
context!.fill(rect);
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
Everywhere for the segments the below code can be used
self.mySegment.setSegmentStyle()