How to set backgroundColor of UISegmentedControl to white in iOS 13

后端 未结 4 1242
温柔的废话
温柔的废话 2021-02-05 07:08

iOS 13 introduced some changes to the UISegmentedControl including a really nice animation when switching the selected segment. However I\'m noticing that it\'s not displaying t

4条回答
  •  情话喂你
    2021-02-05 08:02

    SWIFT 3 & 4+

    From this answer https://stackoverflow.com/a/31652184/3249196 , if you want an all white background without the grey overlay justr replace tintColor and backgroundColor with UIColor.white

    extension UISegmentedControl {
        func removeBorders() {
            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)
        }
    
        // 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!
        }
    }
    

提交回复
热议问题