SwiftUI contentShape 使用

裁剪图片后被裁剪部分仍然可以点击

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct ContentView: View {

@State var count = 0

var body: some View {
Image(systemName: "cube")
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipped()
.contentShape(Rectangle()) // here
.onTapGesture {
print("tapped mainContainer\(count)\n")
count += 1
}
}
}

透明部分无法点击

透明的 view,无论是整体 opacity 设置为了0,还是颜色设置为了 clear,在 swiftUI 中,默认的 content shape (内容形状)就是 0,所以点击事件是无法生效的。

1
2
3
4
5
6
7
8
9
10
11
12
13
struct ContentView: View {
var body: some View {
VStack {
Text("可以点击文字 1")
Spacer()
Text("可以点击文字 2")
}
.contentShape(Rectangle()) // here
.onTapGesture {
print("点击了")
}
}
}

or

1
2
3
4
Color.clear
.frame(width: 300, height: 300)
.contentShape(Rectangle()) // 这里,当然上面的frame也有必要,如果frame为0,则肯定也无法触发点击
.onTapGesture { print("tapped") }

SwiftUI contentShape 使用
https://wonderhoi.com/2025/08/26/SwiftUI-contentShape-使用/
作者
wonderhoi
发布于
2025年8月26日
许可协议