ViewModifiers: Shrinking views

Some simple modifiers to shrink views on tap or long press

These are some simple view modifiers that add shrinking customizable animations to the tap gesture or the long press gesture of any view.

I find these modifiers pretty useful when trying to add some interactions to my UIs.

Table Of Contents:

Demo

In this video:

  • The plus image has the LongPressShrink modifier, so the count increases once the LongPress gesture is successfully finished (0.5 seconds of continuous tap).
  • The Increase Count Text has the TapShrink modifier, so the count increases once the tap gesture ends.

TapShrinkModifier

Usage:

someView
    .shrinkOnTap {
        // This will be executed once the tap gesture finishes.
        print("Tapped")
    }

LongPressShrinkModifier

Usage:

someView
    .shrinkOnLongPress {
        // This will be executed once the user long pressed the view for the given time.
        // (0.5s by default).
        print("Long Press Finished")
    }

The Code from the video:

If you want to try it out, just create some files with the view modifiers code from above. Here is the code from the Preview in the Demo Video:

struct ContentView: View {
    @State private var count: Int = 0

    var body: some View {
        VStack {
            Image(systemName: "plus")
                .resizable()
                .frame(width: 50, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                .foregroundStyle(.tint)
                .shrinkOnLongPress {
                    count += 1
                }

            Text("Increase Count")
                .font(.title3)
                .foregroundStyle(.secondary)
                .shrinkOnTap {
                    count += 1
                }
                .padding(.bottom)

            Text("Count: \(count.description)")
                .foregroundStyle(.black)
        }
        .padding()
        .imageScale(.large)
    }
}

#Preview {
    ContentView()
}

Some key aspect to consider here, would be accessibility, given the components to which we are applying the modifiers are not buttons, we are losing the default accessibility features that Apple provides when using the Button component.

Related: Tap Gesture vs Button by David Yang.


Related Articles

ViewModifiers: Shrinking views | manu.show
Tags: iOS
Share: Twitter LinkedIn