How to change the colors of a segment in a UISegmentedControl in iOS 13?

前端 未结 14 828
醉话见心
醉话见心 2020-11-30 18:13

A UISegmentedControl has a new appearance in iOS 13 and existing code to alter the colors of the segmented control no longer work as they did.

Prior to

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 18:35

    As of Xcode 11 beta 3

    There is now the selectedSegmentTintColor property on UISegmentedControl.

    Thank you @rmaddy!


    Original answer, for Xcode 11 beta and beta 2

    Is there a proper solution, using public APIs, that doesn't require digging into the private subview structure?

    With Xcode 11.0 beta, it seems to be a challenge to do it by-the-rules, because it basically requires to redraw all the background images for every states by yourself, with round corners, transparency and resizableImage(withCapInsets:). For instance, you would need to generate a colored image similar to:

    So for now, the let's-dig-into-the-subviews way seems much easier:

    class TintedSegmentedControl: UISegmentedControl {
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            if #available(iOS 13.0, *) {
                for subview in subviews {
                    if let selectedImageView = subview.subviews.last(where: { $0 is UIImageView }) as? UIImageView,
                        let image = selectedImageView.image {
                        selectedImageView.image = image.withRenderingMode(.alwaysTemplate)
                        break
                    }
                }
            }
        }
    }
    

    This solution will correctly apply the tint color to the selection, as in:

提交回复
热议问题