【问题标题】:SwiftUI Preview: Preview failed if Custom ButtonStyle is in other fileSwiftUI 预览:如果自定义按钮样式在其他文件中,则预览失败
【发布时间】:2020-10-09 05:46:28
【问题描述】:

我的自定义按钮样式如下所示。

struct DefaultButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .frame(minWidth: 0, maxWidth: .infinity)
            .foregroundColor(.white)
            .background(RoundedRectangle(cornerRadius: 4)
                .fill(configuration.isPressed ? Color.black : Color.green)
            )
    }
}

使用自定义按钮样式的示例实现。

Button(action: { self.viewModel.login() }) {
  Text("Sign In")
    .font(.headline)
}
.buttonStyle(DefaultButtonStyle())
.frame(minWidth: 0, maxWidth: 380)
.padding([.leading, .trailing], 27.5)

我的预览代码。

#if DEBUG
struct LoginView_Previews: PreviewProvider {
    static var previews: some View {
        LoginView (viewModel: LoginViewModel()).environment(\.verticalSizeClass, .regular)
    }
}
#endif

当我将自定义样式与视图放在同一个文件中时。预览没问题。 但是当我将自定义样式移到它自己的文件中时(为了在整个应用程序中重用它)。预览抛出错误。

Compiling failed: type 'Any' has no member 'leading'

我是否必须在 LoginView_Previews 中添加一些内容才能使其在预览中加载?我做错了什么?

【问题讨论】:

    标签: xcode swiftui


    【解决方案1】:

    我想这是由于与内置 DefaultButtonStyle 冲突,所以以某种方式命名你的名字,比如

    struct MyDefaultButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
        // .. other code
    
    ...
    
    Button(action: { self.viewModel.login() }) {
      Text("Sign In")
        .font(.headline)
    }
    .buttonStyle(MyDefaultButtonStyle())
    

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2020-12-11
      相关资源
      最近更新 更多