简体   繁体   中英

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.

You define custom style in makeBody function. You can use configuration.isPressed to configure the button in a slightly different way when it's pressed.

struct MyButtonStyle: ButtonStyle {

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            // all of the modifiers you want to apply in your custom style e.g.:
            .foregroundColor(configuration.isPressed ? .red : .blue)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM