SwiftUI onTapGesture 在透明區塊的偵測問題

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("真的可以按")
}
}
}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com