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
,透明、没有“副作用”。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2019-05-30 Django:永别了pycrypto库~