0

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.