【问题标题】:Error: Return from initializer without initializing all stored properties in SwiftUI Project?错误:从初始化程序返回而不初始化 SwiftUI 项目中的所有存储属性?
【发布时间】:2021-06-28 19:32:03
【问题描述】:

我的 SwiftUI 代码中有以下代码:

@Binding var tabSelection: Int

    
init() {

UINavigationBar.appearance().barTintColor = .clear
UINavigationBar.appearance().backgroundColor = .clear; UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().shadowImage = UIImage()
      
}

但是当我尝试编译我的代码时,我得到了这个错误:

如果我删除此代码,我可以成功编译我的应用程序:

init() {

UINavigationBar.appearance().barTintColor = .clear
UINavigationBar.appearance().backgroundColor = .clear; UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().shadowImage = UIImage()
      
}

有人可以就这个问题提出建议吗?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    通常当您创建 View 时,因为它是 struct,Xcode 会为您合成初始化程序。这意味着您将 Binding 作为参数传入,它会自动为您设置。

    在这种情况下,既然您已经确定了自己的init,那么您还必须采用该Binding 参数并初始化您自己的属性。

    
    struct MyView : View {
        @Binding var tabSelection: Int
        
        init(tabSelection: Binding<Int>) {
            _tabSelection = tabSelection //<-- Here (have to use the underscore because of the `@Binding` -- see the link later in the post
            
            UINavigationBar.appearance().barTintColor = .clear
            UINavigationBar.appearance().backgroundColor = .clear; UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
            UINavigationBar.appearance().shadowImage = UIImage()
        }
        
        var body: some View {
            Text("Hello, world!")
        }
    }
    
    

    另请参阅:SwiftUI: How to implement a custom init with @Binding variables

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 2015-06-22
      • 2017-12-31
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多