【问题标题】:How to Customize SwiftUI SegmentedPicker如何自定义 SwiftUI SegmentedPicker
【发布时间】:2020-11-25 21:37:02
【问题描述】:

我在 SwiftUI 中使用 SegmentedPicker 样式的 Picker。

我正在尝试更改选择器的颜色,并在 stackoverflow 中找到了此代码。 How to change selected segment color in SwiftUI Segmented Picker

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

但是弹出一个错误说“从初始化程序返回而不初始化所有存储的属性”

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

【问题讨论】:

    标签: ios swift swiftui swiftui-list


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 感谢您的帮助!但我刚开始学习 swiftUI,所以我不确定你的意思。那么我可以添加另一个 .swift 文件并添加一个视图结构,然后将上面的代码粘贴到结构中吗?或者我应该把它放在另一个结构视图中的初始化函数中,在那里我在另一个视图中自定义了导航栏的设置?
      • 当您创建应用程序时,会自动创建一个名为“[yourappname]App.swift”的文件。在文件中,它可能会在某处说“@main”,这基本上意味着当您构建应用程序并将其运行到设备时,应用程序的起点将是该文件。您可以将 init 函数放入该文件中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 2021-01-04
      相关资源
      最近更新 更多