Can i not use switch to check for a variable and implement a view based on the variable’s value. I tried using if else as well but still getting the same error. Do I have to create a method and return a view for the same and use it here?
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
}
2
Answers
You’re using this modifier https://developer.apple.com/documentation/swiftui/view/background(_:alignment🙂, it requires a
View
as parameter not a function or closure.The modifier is deprecated since iOS 15. If your app is targeted iOS 15 and above, you can use this new modifier https://developer.apple.com/documentation/swiftui/view/background(alignment:content🙂
In case of below iOS 15, you should wrap your label by your
switcher
Result
Or Even Shorter