简体   繁体   中英

How to animate overlay in SwiftUI

I have a button with an overlay of a rounded rectangle with a corner radius and stroked with a lineWidth of 1.0. This is being done in a custom ButtonStyle.

func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .background(Color.green)
            .cornerRadius(5)
            .scaleEffect(configuration.isPressed ? 0.9 : 1)
            .animation(.easeOut)
            .overlay(
                RoundedRectangle(cornerRadius: 4)
                    .stroke(Color.blue, lineWidth: 1)
            )
    }

The issue with the method configuration above is that when the button is tapped, it animates the button except the overlay. The border here stays there and doesn't animate with the content of the button. Anyone know why/how to fix it?

Well, the answer is simple. The order of modifiers matter. The following actually solved the issue. Pretty much moved the overlay as the first modifier.

func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .overlay(
                RoundedRectangle(cornerRadius: 5)
                    .stroke(borderStrokeColor, lineWidth: borderLineWidth)
            )
            .background(color)
            .cornerRadius(cornerRadius)
            .scaleEffect(configuration.isPressed ? 0.9 : 1)
            .animation(.easeOut)
    }

The animation works smoothly as it should:)

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