swift 获取错误:表达式列表中需要表达式

llmtgqce  于 2023-01-12  发布在  Swift
关注(0)|答案(2)|浏览(316)

我不能使用switch来检查变量并基于变量的值实现视图吗?我也尝试使用if else,但仍然得到相同的错误。我必须创建一个方法并返回相同的视图,然后在这里使用它吗?

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
}

zaqlnxep

zaqlnxep1#

甚至更短

.background(content: {
    switch self.type {
    case .info:
        Color.blue
    case .error:
        Color.red
    case .warning:
        Color.yellow
    }
})
vm0i2vca

vm0i2vca2#

你正在使用这个修饰符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 Package 您的标签

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

结果

相关问题