SwiftUI-Xcode-VStack无法推断类型

我正在尝试在Xcode中创建一个简单的主/详细应用程序。

我希望详细视图是

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

但我知道

Generic parameter 'Content' could not be inferred

IDE为我提供了修复程序,但是如果这样做,它会写一个我必须填写的通用类型,但随后会出现其他错误,例如f.i。如果我将AnyView或TupleView放进去。

我希望它可以推断一切,它不能理解的错误是什么?

iCMS 回答:SwiftUI-Xcode-VStack无法推断类型

在SwiftUI中,通常不需要引用控件。您可以在视图中直接将修饰符应用于它们。

这是首选的方式:

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

或者,如果需要,您可以将控件提取为单独的变量:

struct ContentView: View {
    var body: some View {
        let hstack = HStack {
            button
        }
        return VStack {
            hstack
        }
    }

    var button: some View {
        Button("Click me") {
            // some action
        }
    }
}

但是最后,我绝对建议您阅读Apple SwiftUI tutorials

本文链接:https://www.f2er.com/1872784.html

大家都在问