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 效果就和我预期的一样了:


相关推荐
struggle202516 小时前
Ollmao (OH-luh-毛程序包及源码) 是一款原生 SwiftUI 应用程序,它与 Ollama 集成,可在 Mac 上本地运行强大的 AI 模型
ios·swiftui·swift
货拉拉技术1 个月前
货拉拉用户端SwiftUI踩坑之旅
ios·swiftui·swift
ZacJi1 个月前
巧用 allowsHitTesting 自定义 SignInWithAppleButton
ios·swiftui·swift
刘争Stanley1 个月前
SwiftUI 是如何改变 iOS 开发游戏规则的?
ios·swiftui·swift
1024小神1 个月前
在swiftui中使用Alamofire发送请求获取github仓库里的txt文件内容并解析
ios·github·swiftui
大熊猫侯佩1 个月前
SwiftUI 撸码常见错误 2 例漫谈
swiftui·xcode·tag·tabview·preview·coredata·fetchrequest
东坡肘子2 个月前
肘子的 Swift 周报 #063|异种肾脏移植取得突破
swiftui·swift·apple
恋猫de小郭2 个月前
什么?Flutter 可能会被 SwiftUI/ArkUI 化?全新的 Flutter Roadmap
flutter·ios·swiftui
靴子学长2 个月前
iOS + watchOS Tourism App(含源码可简单复现)
mysql·ios·swiftui
hxx2212 个月前
iOS swift开发系列--如何给swiftui内容视图添加背景图片显示
ios·swiftui·swift