简体   繁体   中英

SwiftUI how to factor out animation from ButtonStyle so it can be reused

On my custom button style for macOS i use an animation which i want to factor out and use on other buttons / buttonStyles

i came up with this solution, which however for some reason doesn't animate

struct FButtonAnimation: ViewModifier {
    
    @State var configuration: ButtonStyleConfiguration
    
    func body(content: Content) -> some View {
        content
            .scaleEffect(configuration.isPressed ? 0.9 : 1)
            .animation(.easeOut(duration: 0.2), value: configuration.isPressed)
    }
    
}

struct FButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .frame(maxWidth: .infinity)
            .padding([.top, .bottom], 6)
            .foregroundColor(configuration.role == .cancel ? Color.black : Color.white)
            .background((configuration.role == .cancel ? Color.white : Color.accentColor).opacity(configuration.isPressed ? 0.8 : 1) )
            .cornerRadius(6)
            .shadow(color: .black.opacity(0.25), radius: 2, x: 0, y: 0.5)
            .modifier(FButtonAnimation(configuration: configuration))
    }
}

So how to factor out the animation so it can be reused?

Try to remove state wrapper

struct FButtonAnimation: ViewModifier {
    
    var configuration: ButtonStyleConfiguration    // << here !!

    // ...
}

演示

Tested with Xcode 13.4 / iOS 15.5

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