Is there a way to detect when a UI element is touched and held?

For example, I've got some custom UI that I want to change color when it's touched and keep the color until the touch is released.

Replies

I don't think that's what I'm really looking for...


I want to be able to tell when the the element is touched and when it loses touch.

I belive you want a combination of `LongPressGesture` (with the minimum press duration set to zero) and `onEnded` to know when the press has ended...


https://developer.apple.com/documentation/swiftui/longpressgesture


https://developer.apple.com/documentation/swiftui/gestures/adding_interactivity_with_gestures

With the following;


     var body: some View {
        let padGesture = LongPressGesture(minimumDuration: 0.1, maximumDistance: 100)
            .onEnded { _ in
                self.color = self.defaultColor
            }
            .onChanged { _ in
                self.color = self.activeColor
        }
        return Rectangle()
            .onAppear{
                self.color = self.defaultColor
            }
            .foregroundColor(self.color)
            .gesture(padGesture)
    }


When the pad is pressed then it changes color to activeColor but after minimumDuration it resets to defaultColor.

Thanks for the suggestion, I'll look into implementing this with UIKit although would be nice to be able to do it in SwiftUI

Please file a radar on this! This is a very common use case, and it shouldn't be as confusing as it is...


You should be able to get this working using an extremely long minimumDuration and using the "pressing:" parameter on the longPressAction:

myView.longPressAction(minimumDuration: 100000, 
                       maximumDistance: 100, 
                       { print("Action: this is called when pressed for the duration") }, 
                              pressing: {pressed in print("This is called when the press starts/stops")})


Put your coloring code in a closure you add to the pressing: parameter...