SwiftUI的Init方法不适用于ObservedObject声明

时间:2019-12-03 00:54:08

标签: ios swift xcode swiftui swift5

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

我正在尝试更改UI选项卡栏的背景颜色,但是每次我添加覆盖该方法的init时,都会开始忽略诸如“传递给不带参数的调用的参数”之类的错误。

我在下面附上了一段控制器代码。感谢您为解决此问题提供的任何帮助。

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

2 个答案:

答案 0 :(得分:1)

由于您的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
     }

}

答案 1 :(得分:-1)

尝试: (我必须创建一个虚拟类,因为您没有提供用于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()
    }
}