'How to conform the ButtonStyle protocol in SwiftUI?
I'd like to create a custom button in SwiftUI that I want to reuse throughout the app. The button is basically just a clickable image with no label on it. I thought about creating a custom ButtonStyle for it. Though, I have problems conforming the ButtonStyle protocol as don't know which type I should choose here.
I already tried some View or just View for <#type> but that didn't work out.
struct customButtonStyle: ButtonStyle {
typealias Body = <#type>
}
The error messages I get when trying to use View or some View is:
Type 'customButtonStyle' does not conform to protocol 'ButtonStyle' and XCode just adds this line typealias Body = <#type> again.
Thanks so much in advance for your help.
Solution 1:[1]
If you want to create a custom style for a button, this is one way to do it working with SwiftUI 3 and Swift 5.5:
Create your styles:
extension View {
// Theme 1
func theme1ButtonStyle() -> some View {
self.modifier(Theme1ButtonStyle())
}
// Theme 2
func themeBlueButtonStyle() -> some View {
self.modifier(ThemeBlueButtonStyle())
}
}
The modifiers of each style (I'll write only 1, you get the idea):
struct ThemeBlueButtonStyle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.headline)
.foregroundColor(Color.white)
.shadow(color: .black, radius: 2)
.cornerRadius(10)
}
}
You can call it like:
Text("SIGN UP")
.themeBlueButtonStyle()
Solution 2:[2]
It looks like in iOS 15, the ButtonStyle protocol is gone, so you cannot do this. Instead, you have to accept the list of pre-made button styles, and the only way to customize is through ViewModifiers... I couldn't find anything about it in the Apple documentation :(
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arturo |
| Solution 2 | marhab |
