如何自定义 SwiftUI 分段选择器

How to Customize SwiftUI SegmentedPicker

我在 SwiftUI 中使用 SegmentedPicker 风格的 Picker。

我正在尝试更改选择器的颜色,并在 Whosebug 中找到了这段代码。

init() {
    UISegmentedControl.appearance().selectedSegmentTintColor? = .blue
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .normal)
}

但是会弹出一个错误提示“Return 来自初始值设定项而不初始化所有存储的属性”

我该怎么做才能使错误消失:(

如果您要在 LoginSheetView 的 init 中调用它,您还需要在 init 函数中设置所有其他变量。

当您设置 UISegmentedControl.appearance() 时,它会在您的应用程序中为所有 UISegmentedControl 全局设置外观。因此,由于不需要在 LoginSheetView 中调用它,因此简单的解决方案是将此 init 移动到没有其他 init 变量的初始视图之一,例如您 @main 所在的 ___App.swift 文件被调用。

如果您提供自己的 init() 方法,则必须初始化所有属性。由于几乎每个 属性 都有一个默认值,您只需初始化绑定即可使您的代码正常工作...

init(showLoginView: Binding<Bool>) {
    self._showLoginView = showLoginView //<< here init your stored properties

    UISegmentedControl.appearance().selectedSegmentTintColor? = .blue
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
    UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .normal)
}