vasily
vasily

Reputation: 2920

Long press animation with Swift UI

I have a long press gesture that highlights another button. The code looks like the following:

@GestureState var highlight = false

var body: some View {
    var longPress: some Gesture {
        LongPressGesture(minimumDuration: 3)
            .updating($highlight) { currentstate, gestureState, transaction in
                gestureState = currentstate
                transaction.animation = Animation.easeInOut(duration: 2.0)
            }
    }
    Text("highlight!")
        .gesture(longPress)
    Button(...) { ... }
        .accentColor(self.highlight ? .green : .none)                   
}

How do I make sure that the transitions from .none accent to .green accent and back are more smooth? At the moment it switches rather abruptly.

Upvotes: 5

Views: 1894

Answers (1)

Asperi
Asperi

Reputation: 257711

The .accentColor is not animatable modifier, however you can achieve the same effect (as soon as I understood) with the following approach.

demo

struct TestLongPressGesture: View {
    @GestureState var highlight = false
    var body: some View {
        var longPress: some Gesture {
            LongPressGesture(minimumDuration: 3)
                .updating($highlight) { currentstate, gestureState, transaction in
                    transaction.animation = Animation.easeInOut(duration: 2.0)
                    gestureState = currentstate
                }
        }
        return VStack {
            Text("highlight!")
                .gesture(longPress)
            Divider()
            Button("Button") { }
                .font(Font.largeTitle.bold())
                .foregroundColor(.white)
                .colorMultiply(self.highlight ? .green : .blue)
                .animation(.easeInOut, value: highlight)
        }
    }
}

Upvotes: 2

Related Questions