UISegmentedControl
在iOS 13中有了新的外观,用于更改分段控件的颜色的现有代码不再像以前那样工作。
在iOS 13之前,您可以设置tintColor
和,它将用于分段控件周围的边框、线段之间的线条以及所选线段的背景色。然后,您可以使用titleTextAttributes
的前景颜色属性来更改每个片段标题的颜色。
在iOS 13下,tintColor
什么也不做。您可以设置分段控件的backgroundColor
来更改分段控件的整体颜色。但是我找不到任何方法来改变所选片段的背景颜色。设置文本属性仍然有效。我甚至尝试设置标题的背景颜色,但这只会影响标题的背景,而不会影响所选片段的其余背景颜色。
简而言之,如何在iOS 13中修改当前选定的UISegmentedControl
段的背景色?有没有一种适当的解决方案,使用公共API,而不需要深入研究私有子视图结构?
iOS 13中没有针对UISegmentedControl
或UIControl
的新属性,并且UIView
中的任何更改都不相关。
发布于 2019-07-04 00:24:43
从iOS 13b3开始,UISegmentedControl
上现在有一个selectedSegmentTintColor
。
若要更改分段控件的整体颜色,请使用其backgroundColor
。
要更改选定线段的颜色,请使用selectedSegmentTintColor
。
要更改未选中段标题的颜色/字体,请使用状态为.normal
/UIControlStateNormal
的setTitleTextAttributes
。
要更改所选段标题的颜色/字体,请在状态为.selected
/UIControlStateSelected
的情况下使用setTitleTextAttributes
。
如果创建包含图像的分段控件,如果图像是作为模板图像创建的,则分段控件的tintColor
将用于为图像着色。但这有一个问题。如果您将tintColor
设置为与selectedSegmentTintColor
相同的颜色,则图像在所选片段中将不可见。如果将tintColor
设置为与backgroundColor
相同的颜色,则未选定分段上的图像将不可见。这意味着图像的分段控件必须使用3种不同的颜色才能使所有内容可见。或者,您可以使用非模板图像,而不设置tintColor
。
在iOS 12或更早版本下,只需设置分段控件的tintColor
或依赖于应用程序的整体色调颜色。
发布于 2019-10-23 19:17:57
IOS 13和Swift 5.0 (Xcode 11.0)段控制100%工作
if #available(iOS 13.0, *) {
yoursegmentedControl.backgroundColor = UIColor.black
yoursegmentedControl.layer.borderColor = UIColor.white.cgColor
yoursegmentedControl.selectedSegmentTintColor = UIColor.white
yoursegmentedControl.layer.borderWidth = 1
let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
yoursegmentedControl.setTitleTextAttributes(titleTextAttributes, for:.normal)
let titleTextAttributes1 = [NSAttributedString.Key.foregroundColor: UIColor.black]
yoursegmentedControl.setTitleTextAttributes(titleTextAttributes1, for:.selected)
} else {
// Fallback on earlier versions
}
发布于 2019-09-25 01:56:52
@Ilahi Charfeddine的Swift版本回答:
if #available(iOS 13.0, *) {
segmentedControl.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
segmentedControl.selectedSegmentTintColor = UIColor.blue
} else {
segmentedControl.tintColor = UIColor.blue
}
https://stackoverflow.com/questions/56436559
复制相似问题