运用 clipped() 裁切视图后,虽然视图的显现区域变小了,可是点击区域却仍是被裁前的区域。因而假如有的视图需要裁剪后要接纳接触事情,需要做一下处理。

举例说明

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

Rectangle()
  .fill(.orange.gradient)
  .frame(width: 300, height: 300)
  // Set view to 100100 → renders out of bounds
  .frame(width: 100, height: 100)
  .border(.blue)
SwiftUI Tips: clipped()后hit testing区域不会变

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

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
                }
        }
    }
}

效果如下,能够看到点击按钮的事情没有被正确的承受,仍是算到了矩形上:

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

修复:运用 .contentShape()

运用 contentShape 办法能够设置 view 的点击响应区域。因而在裁剪后假如加上 .contentShape() 后就能够得到正确的点击区域。

Rectangle()
    .fill(.orange.gradient)
    .frame(width: 300, height: 300)
    .frame(width: 100, height: 100)
    .clipped()
    .contentShape(Rectangle())

在设置完 contentShape 效果就和我预期的相同了:

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