Getting error : Expected expression in list of expressions

Getting error : Expected expression in list of expressions

我可以不使用 switch 来检查变量并根据变量的值实现视图吗?我也尝试使用 if else 但仍然出现相同的错误。我是否必须为此创建一个方法和 return 视图并在此处使用它?

struct AppThemeButton: View {

    var action: (() -> Swift.Void)?
    var buttonType: ThemeButtonType = .bordered

    var body: some View {
        Button {
            // button action
            if let act = action {
                act()
            }
        
        } label: {
            Text("+ \(TextStrings.addAProject.localized())")
                .frame(maxWidth: .infinity, maxHeight: .infinity, 
alignment: .center)
                .background(
                    switch self.buttonType {
                    case .bordered:
                        Color.green
                    case .colored:
                        Color.red
                    }
                )
                .frame(height: 60, alignment: .center)
                .padding([.leading, .trailing])
        }
    }
}

enum ThemeButtonType {
    case bordered
    case colored
}

您正在使用此修饰符 https://developer.apple.com/documentation/swiftui/view/background(_:alignment:),它需要一个 View 作为参数,而不是函数或闭包。

该修饰符自 iOS 15 起已弃用。如果您的应用针对 iOS 15 及更高版本,您可以使用此新修饰符 https://developer.apple.com/documentation/swiftui/view/background(alignment:content:)

如果低于iOS 15,你应该用你的switcher

包裹你的标签
enum ThemeButtonStyle: ButtonStyle {
    case filled
    case bordered
    
    func makeBody(configuration: Configuration) -> some View {
        switch self {
        case .filled:
            configuration.label
                .foregroundColor(.white)
                .padding()
                .background(Capsule().fill(.red))
        case .bordered:
            configuration.label
                .foregroundColor(.black)
                .padding()
                .background(Capsule().stroke(.black))
        }
    }
}

struct AppThemeButton: View {
    let style: ThemeButtonStyle
    var body: some View {
        Button {
            print("Touched")
        } label: {
            Text("Touch Me")
        }.buttonStyle(style)
    }
}

struct ThemeButtonStyle_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            AppThemeButton(style: .filled)
            AppThemeButton(style: .bordered)
        }
    }
}

结果