SwiftUI Tips: clipped()后hit testing区域不会变

使用 clipped() 裁切视图后,虽然视图的显示区域变小了,但是点击区域却还是被裁前的区域。因此如果有的视图需要裁剪后要接收触摸事件,需要做一下处理。

举例说明

假设我们把一个300x300矩形的 frame 设置成100x100:

swift 复制代码
Rectangle()
  .fill(.orange.gradient)
  .frame(width: 300, height: 300)
  // Set view to 100×100 → renders out of bounds
  .frame(width: 100, height: 100)
  .border(.blue)

从图上可以看出有边框的部分是实际UI渲染的面积,外面的部分在 frame 外的。如果我们把这个视图裁切后,把一个按钮放置在蓝色边框外,按钮其实会因为被矩形遮挡而接收不了点击事件。

swift 复制代码
struct ContentView: View {
    @State var buttonTapCount = 0
    @State var rectTapCount = 0

    var body: some View {
        VStack {
            Text("buttonTapCount:\(buttonTapCount)")
            Text("rectTapCount:\(rectTapCount)")
            Button("点击无效") {
                buttonTapCount += 1
            }
            .buttonStyle(.borderedProminent)
            
            Rectangle()
                .fill(.orange.gradient)
                .frame(width: 300, height: 300)
                .frame(width: 100, height: 100)
                .clipped()
                .onTapGesture {
                    rectTapCount += 1
                }
        }
    }
}

效果如下,可以看到点击按钮的事件没有被正确的接受,还是算到了矩形上:

修复:使用 .contentShape()

使用 contentShape 方法可以设置 view 的点击响应区域。因此在裁剪后如果加上 .contentShape() 后就可以得到正确的点击区域。

swift 复制代码
Rectangle()
    .fill(.orange.gradient)
    .frame(width: 300, height: 300)
    .frame(width: 100, height: 100)
    .clipped()
    .contentShape(Rectangle())

在设置完 contentShape 效果就和我预期的一样了:


相关推荐
HarderCoder16 小时前
SwiftUI 可复用视图设计解剖:从语义到 API 的完整实践
swiftui·swift
东坡肘子16 小时前
当灵感跑在了结果前面 -- 肘子的 Swift 周报 #145
人工智能·swiftui·swift
霍霍哈嗨5 天前
swiftUI框架基础
ios·swiftui·swift
东坡肘子8 天前
当每一次写入都有了新价格 -- 肘子的 Swift 周报 #144
人工智能·swiftui·swift
CHB14 天前
uni-app x 蒸汽模式 iOS版 性能测试基准报告 Benchmark
ios·uni-app·swiftui
大熊猫侯佩14 天前
SwiftUI 侦探笔记:iPhone 14 失踪的“刘海”与侯佩的像素诡计
swiftui·swift·apple
大熊猫侯佩14 天前
WWDC26 新 @ContentBuilder 修饰符:SwiftUI 终于有了户口本
swiftui·swift·wwdc
东坡肘子15 天前
当 Linux 成为“空气”:容器、Agent 与不再重要的“桌面之争” -- 肘子的 Swift 周报 #143
人工智能·swiftui·swift
东坡肘子22 天前
SPI 加入 Apple,Swift 迈向自举 -- 肘子的 Swift 周报 #142
人工智能·swiftui·swift
神奇的程序员1 个月前
开发了一个进阶版Apple健康
swiftui·apple·apple watch