SwiftUI 使用contentShape()控制點擊區域

當我們向一個view添加TapGesture時,就會發現“有內容”的區域是可以點擊的。“有內容”指的是有圖片、文字、背景顏色的區域。而空白區域,是不能觸發點擊回調的。
比如:

struct ContentView: View {
    var body: some View {
        VStack(spacing: 124) {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .frame(maxWidth: .infinity)
        .background(Color.red)
        .onTapGesture {
            print("tapped!!!")
        }
    }
}


整個紅色區域都可以點擊。

當把 .background(Color.red) 去除時,發現只有圖標和文字能點擊。

struct ContentView: View {
    var body: some View {
        VStack(spacing: 124) {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .frame(maxWidth: .infinity)
        //.background(Color.red)
        .onTapGesture {
            print("tapped!!!")
        }
    }
}

所以,我們得明確告訴view實際的內容區域,用 .contentShape()修飾:

struct ContentView: View {
    var body: some View {
        VStack(spacing: 124) {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .frame(maxWidth: .infinity)
        .contentShape(Rectangle()) // 這裏!
        .onTapGesture {
            print("tapped!!!")
        }
    }
}

現在整個VStack(即使是其中的空白區域)都能點擊。


對於上面的案例,你也可以爲VStack添加一個白色的background,但是有“副作用”,比如系統進入深色模式時,你要想辦法讓其跟上變化。所以我更傾向於選擇使用contentShape,透明、沒有“副作用”。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章