问题
I am trying to set the background color of a segmentedControl in iOS 13 for the normal state.
I have the same issue as listed here: How to set backgroundColor of UISegmentedControl to white in iOS 13
The answer to the question in the link above is not helpful. I would like to maintain the ios13 slide animation behavior but also have the normal state segments to be white not a light gray.
There seems to be a default image in the segmentedControl that is causing the gray/offWhite coloring effect.
i have tried setting the background image as the colors for selected state and normal for UIBarMetrics.default but this just gives me the pre-ios13 behavior
if #available(iOS 13, *) {
guard let selectedTintColor = selectedSegmentTintColor else { return }
let tintColorImage = selectedTintColor.asImage()
let backgroundColor = self.backgroundColor ?? UIColor.clear
setBackgroundImage(backgroundColor.asImage(), for: .normal, barMetrics: .default)
setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
setBackgroundImage(selectedTintColor.withAlphaComponent(0.2).asImage(), for: .highlighted, barMetrics: .default)
setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
}
extension UIImage {
func asImage(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}
//I also added the following to the View
override func layoutSubviews() {
super.layoutSubviews()
subviews.compactMap{ $0 as? UIImageView }.forEach {
$0.isHidden = $0.image == nil
}
}
with the last part (the layoutSubviews) i was able to see the white backgroundColor before making a segment selection. after a segmentedControlDidChange call the white color is gone and also the default selected segment is now gray after the change too. but none of the text is visible anymore...
this info is from my view debugger: the segmentedCOntrol has a bgColor of white -> and it contains a uiImageView for all segments with a clear image and a bgColor of nil
The selected segment on top of this mentioned ^^ uiImageView has the correct selectedSegmentTintColor as an additional uiImageView and still with a backgroundColor of nil but the image has the correct tint color in it
After all my efforts i am getting the same behavior as the person in the link abov. In the view hierchy it shows the backgorund as white and the visual representation shows the correct color.
Is this a bug? Does anyone have a clue how to overcome this issue?
来源:https://stackoverflow.com/questions/58384418/how-to-set-the-ios13-uisegmentedcontrol-backgroundcolor-to-white