首页 > 解决方案 > 为什么没有在旋转的矩形上触发 SwiftUI onTapGuesture{} 修饰符

问题描述

如果我创建一个 100 宽和 20 高的矩形,然后将其旋转 90 度,如果我单击顶部或底部附近的矩形,则不会调用 onTapGuesture{} 修饰符。

似乎 contentShape() 可能与旋转的矩形不对应

let fixView = Rectangle()
            .rotation(self.fixture.currentAngle)
            .fill(self.fixture.color)
            .overlay(Rectangle().rotation(self.fixture.currentAngle).stroke(self.fixture.borderColor, lineWidth: self.fixture.borderWidth).frame(width: overlayWidth, height: overlayHeight))
            .frame(width: width, height: height)
            .position(x: x, y: y )

            .onTapGesture {
                GlobalData.shared.selectedFixture = self.fixture.object
        }

我发现 .onHover{} 也会发生同样的想法 - 它只是在鼠标悬停在形状框架矩形上时触发。

标签: swiftuishapes

解决方案


rotation不会更改接受手势的原始布局框架,因此您必须使用 显式执行此操作.contentShape,如下所示

Rectangle()
    .rotation(self.fixture.currentAngle)
    .fill(self.fixture.color)
    .overlay(Rectangle().rotation(self.fixture.currentAngle).stroke(self.fixture.borderColor, lineWidth: self.fixture.borderWidth).frame(width: overlayWidth, height: overlayHeight))
    .frame(width: width, height: height)
    // << here !! NB to not put this line after .position()
    .contentShape(Rectangle().rotation(self.fixture.currentAngle))  
    .position(x: x, y: y )

    .onTapGesture {
        GlobalData.shared.selectedFixture = self.fixture.object
}

使用 Xcode 11.4 / iOS 13.4 测试

注意:请注意,hittesting 仅适用于不透明部分(以防您的某些颜色清晰)


推荐阅读