iOS Swift:UISegmentedControl色调颜色与标题重叠

时间:2020-06-18 23:21:37

标签: ios swift uisegmentedcontrol swift5

我希望所有以前的iOS版本都具有iOS 13 UISegmentedControl外观。我尝试使用颜色和边框来自定义segmentControl。这是我的代码:

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
        }
    }

上面的代码非常适合iOS13,但对于以前的版本,所选的段tintColor不适用。我为选定的片段设置了“白色”颜色,为背景设置了“灰色”。所选的色调颜色似乎使标题褪色。边框也没有显示。

已附上屏幕截图,所选的片段色调“白色”不正确。看起来标题已经落伍了。 enter image description here

在iOS 13中,它看起来很完美 enter image description here

我尝试了许多解决方案,但没有用。还是有什么办法可以使iOS 13出现在早期版本中?请帮忙。

谢谢!

1 个答案:

答案 0 :(得分:0)

tintColor更改为selectedColor 您的新代码将是:

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
        }
    }

色调颜色->更改视图的整体颜色 选择的颜色->选择对象时更改!

相关问题