I currently have a uisegmentedcontrol element in my VC and have managed to remove the borders by following the thread below. While it works fine, once selected the uisegmentedcontrol section becomes entirely white, including the icon, is there any way to modify that? So the background of the selected section would be whatever colour I specify and the icon becomes white. Thanks in advance for anyone who may help.
The thread mentioned: Swift: How to remove border from segmented control
This is how you can change the background color for selected indicator in UISegmentControl
extension UISegmentedControl{
func removeBorders() {
setBackgroundImage(imageWithColor(color: .clear), for: .normal, barMetrics: .default)
setBackgroundImage(imageWithColor(color: .gray), for: .selected, barMetrics: .default)
setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
}
// 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!
}
}
As you can see in removeBorders
function you are setting background image based on color for normal
and selected
state. So here you can use whatever color you like.