iosswiftuisegmentedcontroluicolorios13.2

UIControlSegment background color is not transparent anymore on iOS13


I have a UISegmentedControl. it was working fine before iOS13 (I set both backgroundColor and tintColor to clear). But now, I don't get the same result. My SegmentedControl has a light grey layer. I made some research but nothing work. (I have the same problem as this: https://forums.developer.apple.com/thread/123955)

Previous state:

enter image description here

current state - iOS13:

enter image description here


Solution

  • thanks @Maulik Pandya for the answer, I have improve your answer little bit.

    extension UISegmentedControl {
      func clearBG() {
        let clearImage = UIImage().imageWithColor(color: .clear)
        setBackgroundImage(clearImage, for: .normal, barMetrics: .default)
        setBackgroundImage(clearImage, for: .selected, barMetrics: .default)
        setDividerImage(clearImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
      }
    }
    
    public extension UIImage {
      public func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage()}
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
      }
    }