UISegmentedControl
在iOS 13中有了新的外观,用于更改分段控件的颜色的现有代码不再像以前那样工作。
在iOS 13之前,您可以设置tintColor
和,它将用于分段控件周围的边框、线段之间的线条以及所选线段的背景色。然后,您可以使用titleTextAttributes
的前景颜色属性来更改每个片段标题的颜色。
在iOS 13下,tintColor
什么也不做。您可以设置分段控件的backgroundColor
来更改分段控件的整体颜色。但是我找不到任何方法来改变所选片段的背景颜色。设置文本属性仍然有效。我甚至尝试设置标题的背景颜色,但这只会影响标题的背景,而不会影响所选片段的其余背景颜色。
简而言之,如何在iOS 13中修改当前选定的UISegmentedControl
段的背景色?有没有一种适当的解决方案,使用公共API,而不需要深入研究私有子视图结构?
iOS 13中没有针对UISegmentedControl
或UIControl
的新属性,并且UIView
中的任何更改都不相关。
发布于 2021-03-15 00:30:41
SwiftUI Picker
缺少一些基本选项。对于试图在iOS 13或14的SwiftUI中使用SegmentedPickerStyle()自定义选取器的人来说,最简单的选择是使用UISegmentedControl.appearance()
来全局设置外观。下面是一个示例函数,可以调用该函数来设置外观。
func setUISegmentControlAppearance() {
UISegmentedControl.appearance().selectedSegmentTintColor = .white
UISegmentedControl.appearance().backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.1)
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal)
UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
}
但是,如果您想要多个具有不同设置的控件,则使用UISegmentedControl.appearance()
全局设置外观选项并不是很好。另一种选择是为UISegmentedControl
实现UIViewRepresentable
。下面的示例设置了原始问题中询问的属性,并将.apportionsSegmentWidthsByContent = true
设置为奖励。希望这能帮你节省一些时间。
struct MyPicker: UIViewRepresentable {
@Binding var selection: Int // The type of selection may vary depending on your use case
var items: [Any]?
class Coordinator: NSObject {
let parent: MyPicker
init(parent: MyPicker) {
self.parent = parent
}
@objc func valueChanged(_ sender: UISegmentedControl) {
self.parent.selection = Int(sender.selectedSegmentIndex)
}
}
func makeCoordinator() -> MyPicker.Coordinator {
Coordinator(parent: self)
}
func makeUIView(context: Context) -> UISegmentedControl {
let picker = UISegmentedControl(items: self.items)
// Any number of other UISegmentedControl settings can go here
picker.selectedSegmentTintColor = .white
picker.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.1)
picker.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal)
picker.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
picker.apportionsSegmentWidthsByContent = true
// Make sure the coordinator updates the picker when the value changes
picker.addTarget(context.coordinator, action: #selector(Coordinator.valueChanged(_:)), for: .valueChanged)
return picker
}
func updateUIView(_ uiView: UISegmentedControl, context: Context) {
uiView.selectedSegmentIndex = self.selection
}
}
https://stackoverflow.com/questions/56436559
复制相似问题