Home > Software design >  SwiftUI view argument in preview missing argument for parameter 'content' in call
SwiftUI view argument in preview missing argument for parameter 'content' in call

Time:01-03

Hi was trying to create a reusable component only with a background gradient, but in the preview is getting an error

this is the component

import SwiftUI

struct Patterns<Content: View>: View {
    @ViewBuilder var content: Content
    
    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(
                    colors: [Color.red, Color.blue]
                ), startPoint: .leading, endPoint: .trailing)
            content
        }
        
    }
}

struct Patterns_Previews: PreviewProvider {
    static var previews: some View {
        Patterns {
            Text("Hello")
        }
    }
}

but the preview looks like this enter image description here

CodePudding user response:

The view builder is actually a wrapper for function generating view, so here is fixed variant:

struct Patterns<Content: View>: View {
    @ViewBuilder var content: () -> Content     // << here !!

    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(
                    colors: [Color.red, Color.blue]
                ), startPoint: .leading, endPoint: .trailing)
            content()                          // << here !!
        }

    }
}

Tested with Xcode 13.2 / iOS 15.2

  • Related