简体   繁体   中英

iOS Swift: UISegmentedControl Tint Colour overlaps with the title

I wanted the iOS 13 UISegmentedControl appearance for all previous iOS versions. I tried to customise the segmentControl with the color and border. Here's my code:

private func create(_ items: [String]) {
        segmentControl.backgroundColor = .lightGray
        segmentControl.cornerRadius = 10
        segmentControl.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.04).cgColor
        segmentControl.borderWidth = 0.5
        items.enumerated().forEach { (index, item) in
            segmentControl.setTitle(item, forSegmentAt: index)
            if let titleAttributes = titleAttributes {
                segmentControl.setTitleTextAttributes([.foregroundColor: titleAttributes.color, .font: titleAttributes.font], for: .normal)
            }
        }
        if #available(iOS 13.0, *) {
            segmentControl.selectedSegmentTintColor = .white
        } else {
            segmentControl.tintColor = .white
        }
    }

The above code works perfect for iOS13, but for the previous versions, the selected segment tintColor is not appropriate. I have set 'white' color for selected segment and 'gray' for the background. The selected tint color appears to fade the title. The borders also not showing.

Attached is the screenshot, The selected segment tint 'white' is not correct. Looks like title has gone behind. 在此处输入图像描述

Whereas in iOS 13, it looks perfect在此处输入图像描述

I have tried many solutions, it is not working. Or is there any way to give iOS 13 appearances to the earlier versions also? Please help.

Thanks!!!

change tintColor to selectedColor your new code will be:

private func create(_ items: [String]) {
        segmentControl.backgroundColor = .lightGray
        segmentControl.cornerRadius = 10
        segmentControl.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.04).cgColor
        segmentControl.borderWidth = 0.5
        items.enumerated().forEach { (index, item) in
            segmentControl.setTitle(item, forSegmentAt: index)
            if let titleAttributes = titleAttributes {
                segmentControl.setTitleTextAttributes([.foregroundColor: titleAttributes.color, .font: titleAttributes.font], for: .normal)
            }
        }
        if #available(iOS 13.0, *) {
            segmentControl.selectedSegmentTintColor = .white
        } else {
            segmentControl.selectedColor = .white
        }
    }

tint color -> change the whole color of view selected color -> changes when the object is selected !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM