Learn Courses My Dashboard

Please help SWIFT LONG PRESS vs PRESS

Please help… I am new to SWIFT and I need some help… I have the following code and I need to somehow change it so I can catch a LONG PRESS vs a PRESS. I am very new to this so if you can give me detailed help it would be great.


var body: some View {
        ZStack(alignment: .bottom) {
            
            Color.black.ignoresSafeArea()
            
            VStack {
                HStack {
                    Spacer()
                    Text(currentValue)
                        .foregroundColor(.white)
                        .font(.system(size: 72))
                }
                .padding()
                
                ForEach(buttons, id: \.self) { row in
                    HStack {
                        ForEach(row, id: \.self) { button in
                            Button {
                                buttonTapped(button: button)
                            } label: {
                                HStack {
                                    Text(button.rawValue)
                                        .foregroundColor(button.foregroundColor)
                                        .font(.system(size: 30, weight: .semibold))
                                        .frame(width: button.getButtonWidth(), height: button.getButtonWidth())
                                    
                                    if(button.isZeroButton) {
                                        Spacer()
                                    }
                                }
                                .frame(width: button.width, height: button.height)
                                .background(button.backgroundColor)
                                .cornerRadius(button.height)
                            }
                        }
                    }
                }
            }
            .padding(.bottom)
        }
    }

@johnathansmith1969

Welcome to the community.

Maybe rather than use Buttons which wont trap a Tap as opposed to a Long Press, you may have to attach an .onTapGesture and an .onLongPressGesture to your object that you are displaying. Sample code below:

struct ContentView: View {
    @State private var message = "No tap yet"

    var body: some View {
        VStack(spacing: 30) {
            Text(message)
                .padding()
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .fill(.red)
                    .frame(width: 100, height: 55)
                Text("Tap Here")
            }
            .onTapGesture {
                message = "Tap occurred."
            }
            .onLongPressGesture(minimumDuration: 1) { // Duration is in seconds
                message = "Long Press occurred"
            }
        }
    }
}