I'm Joe Too
I'm Joe Too

Reputation: 5840

Add Sample View to PreviewProvider for Custom Wrapper View

I have created a "wrapper" view to handle some standard branding like background color, etc which takes a View as a parameter, but I can't figure out how to pass a sample View in PreviewProvider to see it live in Xcode. This wrapper view works when I build it in the simulator - I just can't figure out how to preview it.

Wrapper View

import SwiftUI

struct BackgroundView<Content: View>: View {
  let contentView: Content
  
  init(@ViewBuilder content: @escaping () -> Content) {
    self.contentView = content()
  }
  
  var body: some View {
    ZStack {
      GeometryReader { geo in
        HStack {
          Spacer()
          Image("Background Watermark")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 0.7 * geo.size.width, height: geo.size.height, alignment: .topLeading)
        }
      }
      VStack {
        self.contentView
      }
    }
    .background(Color("Purple"))
    .edgesIgnoringSafeArea(.top)
  }
}

// This is where I'm struggling
struct BackgroundView_Previews: PreviewProvider {
  static var previews: some View {
    BackgroundView(content: ... )
  }
}

What I've Tried

I tried passing a simple Text to it, but get Cannot convert value of type 'Text' to expected argument type '() -> Content'

static var previews: some View {
  BackgroundView(content: Text("Hello, world"))
}

Then I tried passing a function that returns some View thinking the closure was the issue, but I get Instance member 'sampleTextView' cannot be used on type 'BackgroundView_Previews':

func sampleTextView() -> some View {
  Text("Hello world")
}
static var previews: some View {
  BackgroundView(content: sampleTextView)
}

Any idea what I'm doing wrong or how to load up a simple Text view just to be able to preview this?

Upvotes: 1

Views: 298

Answers (1)

Asperi
Asperi

Reputation: 257693

It is expected to be closure, like

static var previews: some View {
  BackgroundView(content: { Text("Hello, world") })
}

or

static var previews: some View {
  BackgroundView {
    Text("Hello, world")
  }
}

Upvotes: 1

Related Questions