【问题标题】:Add Sample View to PreviewProvider for Custom Wrapper View为自定义包装器视图添加示例视图到 PreviewProvider
【发布时间】:2020-10-06 13:13:23
【问题描述】:

我创建了一个“包装”视图来处理一些标准品牌,如背景颜色等,它以 View 作为参数,但我不知道如何在 PreviewProvider 中传递样本 View在 Xcode 中看到它。当我在模拟器中构建它时,这个包装器视图可以工作 - 我只是不知道如何预览它。

包装视图

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: ... )
  }
}

我的尝试

我尝试将简单的Text 传递给它,但得到Cannot convert value of type 'Text' to expected argument type '() -&gt; Content'

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

然后我尝试传递一个返回 some View 的函数,认为关闭是问题所在,但我得到了 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)
}

知道我做错了什么或者如何加载一个简单的Text 视图以便能够预览吗?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    预计会关闭,喜欢

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      相关资源
      最近更新 更多