David Yang

Tips and posts for iOS developers from an iOS developer.

When trying to execute an action from a user’s tap interaction with an app, you may realize that there are many ways to achieve this, whether you’re developing with UIKit or SwiftUI. I’ll only cover the latter but the same applies to UIKit.

Button

You can just use a button.

Button {
	print("Pressed!")
} label: {
	Text("Press me")
}

You’ll then be able to customize the appearance of your Button and/or its label component in order to match a custom UI design.

If you’re working with UIKit, the component will be a UIButton.

Tap gesture

Or you can also use a tap gesture.

Text("Tap me")
	.onTapGesture {
		print("Tapped!")
	}

Some styling can also be defined on your Text component in order to look exactly like you want.

With UIKit, you can achieve that same behavior with UILabel and a UITapGestureRecognizer.

So which implementation should you choose?

If the same thing can be achieved by both ways, one is still preferred in my opinion.

Usually, just use a Button in most cases for the following reasons:

  • Accessibility: a lot of things are done under the hood by Apple to match accessibility feature such as adding a blue underline on all button texts or even VoiceOver.
  • Buttons are associated with styles and have different states (such as highlighted), which are already implemented by default by Apple.
  • If you chose to customize the states of your CTA (Call To Action), you’ll have much more control over its style by using a Button (and your designer will probably love playing with it).
  • From a pure developer’s standpoint (at least mine), code should speak for itself:
    • a Button serves a purpose, which is user interaction.
    • a Text is displaying some content.
  • By using a Button instead of a tap gesture, the system will always help your users figuring out that an action can be achieved by interacting with it (once again through accessibility, default styles, the platform’s visual cues, etc.).