.selectedSegmentTintColor
defines the selected button color and .layer.backgroundColor
the color for the whole UISegmentedControl background.
It turns out this won't work for background clear or white since on iOS 13 a sort of background image is added on the background and dividers of the segmented control.
A workaround is create an image from color with UIGraphicsGetImageFromCurrentImageContext
. Try this:
class ViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
segmentedControl.setiOS12Layout(tintColor: .red)
}
}
extension UISegmentedControl {
func setiOS12Layout(tintColor: UIColor) {
if #available(iOS 13, *) {
let background = UIImage(color: .clear, size: CGSize(width: 1, height: 32))
let divider = UIImage(color: tintColor, size: CGSize(width: 1, height: 32))
self.setBackgroundImage(background, for: .normal, barMetrics: .default)
self.setBackgroundImage(divider, for: .selected, barMetrics: .default)
self.setDividerImage(divider, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
self.layer.borderWidth = 1
self.layer.borderColor = tintColor.cgColor
self.setTitleTextAttributes([.foregroundColor: tintColor], for: .normal)
self.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
} else {
self.tintColor = tintColor
}
}
}
extension UIImage {
convenience init(color: UIColor, size: CGSize) {
UIGraphicsBeginImageContextWithOptions(size, false, 1)
color.set()
let context = UIGraphicsGetCurrentContext()!
context.fill(CGRect(origin: .zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.init(data: image.pngData()!)!
}
}
Result:
