SwiftUI Init 方法不适用于 ObservedObject 声明

SwiftUI Init method does not work with ObservedObject Declaration

我正在尝试使用 Swift UI 在 Swift 中创建选项卡式应用程序。我正在使用 @ObservedObject 来存储应该呈现的当前视图名称。

我正在尝试更改 UI 选项卡栏的背景颜色,但是每次我添加 init 以覆盖该方法时,都会开始处理 "Argument passed to call that takes no arguments" 等错误。

我附上了下面的控制器代码片段。非常感谢任何解决此问题的帮助。

import SwiftUI

struct ContentView: View {
    @State private var selection = 0

    @ObservedObject var coreRouter: CoreRouter

    init() {
         UITabBar.appearance().backgroundColor = UIColor.blue
     }

    var body: some View {
        TabView(selection: $selection){
            Text("First Screen")
                .font(.title)
                .tabItem {
                    VStack {
                        Image(systemName: "house")
                        Text("Home")
                    }
            }
            .tag(0)
            Text("Second View")
                .font(.title)
                .tabItem {
                    VStack {
                        Image("calendar")
                        Text("New Items")
                    }
            }
            .tag(1)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(coreRouter: CoreRouter())
    }
}

试试这个: (我不得不创建一个虚拟 class,因为你没有提供 corerouter 的代码)

class CoreRouter : ObservableObject {

    @Published var a = false

}

struct ContentView: View {
    @State private var selection = 0

    @ObservedObject var coreRouter: CoreRouter

    init() {
        coreRouter = CoreRouter()
         UITabBar.appearance().backgroundColor = UIColor.blue
     }

    var body: some View {
        TabView(selection: $selection){
            Text("First Screen")
                .font(.title)
                .tabItem {
                    VStack {
                        Image(systemName: "house")
                        Text("Home")
                    }
            }
            .tag(0)
            Text("Second View")
                .font(.title)
                .tabItem {
                    VStack {
                        Image("calendar")
                        Text("New Items")
                    }
            }
            .tag(1)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

由于您的 ContentView 有一个 coreRouter 属性,您的 init 需要接受一个值以分配给 属性;

struct ContentView: View {
    @State private var selection = 0

    @ObservedObject var coreRouter: CoreRouter

    init(coreRouter: CoreRouter) {
         self.coreRouter = coreRouter
         UITabBar.appearance().backgroundColor = UIColor.blue
     }

}