Search code examples
swiftxcodeswiftuivstackhstack

SwiftUI - Xcode - Inferring type not possible for VStack


I am trying to create a simple master/detail app in Xcode.

I want that the detail view is

struct EditingView: View
{
    var body: some View {
        var mainVertical: VStack = VStack() //error here
            {
                var previewArea: HStack = HStack()
                {
                    var editorButton: Button = Button()
                    //the same with return editorButton
                    // I have to add other controls, like a WKWebView
                }
                return previewArea
                //this is a simple version, layout will have other stacks with controls inside
        }
        return mainVertical
    }
}

but I get

Generic parameter 'Content' could not be inferred

The IDE offers me to fix but if I do that, it writes a generic type I have to fill but then other errors come, f.i. if I put AnyView o TupleView.

I would like that it infers everything, what is wrong that it cannot understand?


Solution

  • In SwiftUI you usually don't need to reference your controls. You can apply modifiers to them directly in the view.

    This is the preferred way:

    struct ContentView: View {
        var body: some View {
            VStack {
                HStack {
                    Button("Click me") {
                        // some action
                    }
                }
            }
            .background(Color.red) // modify your `VStack`
        }
    }
    

    Alternatively if needed you can extract controls as separate variables:

    struct ContentView: View {
        var body: some View {
            let hstack = HStack {
                button
            }
            return VStack {
                hstack
            }
        }
    
        var button: some View {
            Button("Click me") {
                // some action
            }
        }
    }
    

    But in the end I definitely recommend you read Apple SwiftUI tutorials