Loading

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,透明、没有“副作用”。

posted @ 2023-05-30 16:33  逆行  阅读(71)  评论(0编辑  收藏  举报