SwiftUI onTapGesture 在透明區塊的偵測問題
Published in
3 min readMar 26
--
App 畫面上的點擊區塊有時會包含透明區塊,就像以下例子的文字框,我們希望使用者可以點擊框框裡的任一個地方。
struct ContentView: View {
var body: some View {
Text("請按按框框裡的透明區塊")
.frame(width: 200, height: 200)
.foregroundColor(.orange)
.padding()
.border(.orange, width: 10)
.onTapGesture {
print("真的可以按")
}
}
}
不過 App 執行後,我們將發現只有點擊文字和框框時會觸發 onTapGesture 的 closure。這是因為 onTapGesture 預設無法偵測到透明區塊的點擊,因此解決的方法有三種。
- 方法 1: 設定 contentShape。
- 方法 2: 改用 Button。
- 方法 3: 設定背景顏色。
設定 contentShape
contentShape 可設定元件點擊的範圍,我們傳入 Rectangle,因此整個框框的區塊都可點擊。
struct ContentView: View {
var body: some View {
Text("請按按框框裡的透明區塊")
.frame(width: 200, height: 200)
.foregroundColor(.orange)
.padding()
.border(.orange, width: 10)
.contentShape(Rectangle())
.onTapGesture {
print("真的可以按")
}
}
}
改用 Button
Button 的整個長方形區域都可點擊,包含透明的區塊。
struct ContentView: View {
var body: some View {
Button {
print("真的可以按")
} label: {
Text("請按按框框裡的透明區塊")
.frame(width: 200, height: 200)
.foregroundColor(.orange)
.padding()
.border(.orange, width: 10)
}
}
}
設定背景顏色
既然問題在透明區塊,我們只要讓它有顏色即可偵測到點擊,因為我們可用 background 設定背景顏色。若是希望背景顏色接近透明的效果,則可將 opacity 設成 0.0001。
struct ContentView: View {
var body: some View {
Text("請按按框框裡的透明區塊")
.frame(width: 200, height: 200)
.foregroundColor(.orange)
.padding()
.border(.orange, width: 10)
.background(content: {
Color(white: 0, opacity: 0.0001)
})
.onTapGesture {
print("真的可以按")
}
}
}