How to make empty space clickable in SwiftUI

May 9, 2024

Question

In SwiftUI, we often use VStack and HStack. But sometimes only text is clickable, while the empty space is not. So, how then can we make the empty space also clickable in SwiftUI?

There are two examples:

// example 1
HStack {
  Text("logout")
}
.onTapGesture {
	print("tap")
}

// example 2
Button(action: {
 	print("tap")
}, label: {
 	HStack {
 		Text("logout")
		Spacer()
	}
})

Both of these examples include click events, but the empty space is not clickable in either of them.

Solution

To make the empty space clickable, just add .contentShape(Rectangle()) to HStack or VStack. However, if there is only Text in the HStack, you need to add Spacer() to fill the empty space.

These are the modified solutions:

// example 1
HStack {
  Text("logout")
  Spacer() // fill the empty space
}
.contentShape(Rectangle()) // make the empty space clickable
.onTapGesture {
	print("tap")
}

// example 2
Button(action: {
 	print("tap")
}, label: {
 	HStack {
 		Text("logout")
		Spacer()
	}
  .contentShape(Rectangle()) // Note that this must be attached right after the HStack, not on the Button
})