drago
drago

Reputation: 1303

Error: Return from initializer without initializing all stored properties in SwiftUI Project?

I have the following code in my SwiftUI code:

@Binding var tabSelection: Int

    
init() {

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

But when I try to compile my code, I get this error:

enter image description here

If I remove this code, I can successfully compile my app:

init() {

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

Could someone please advice on this issue?

Upvotes: 0

Views: 644

Answers (1)

jnpdx
jnpdx

Reputation: 52525

Normally when you created a View, since it's a struct, Xcode synthesizes initializers for you. This means that you pass a Binding in as a parameter and it automatically gets set for you.

In this case, since you've definite your own init, you also have to take that Binding parameter and initialize your own property.


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

See also: SwiftUI: How to implement a custom init with @Binding variables

Upvotes: 4

Related Questions