为什么 SwiftUI onTapGuesture{} 修饰符不会在旋转的矩形上触发

Why is SwiftUI onTapGuesture{} modifier not triggered on a rotated rectangle

如果我创建一个宽度为 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{} 也有同样的想法 - 它只是在鼠标悬停在形状框架矩形上时触发。

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 仅适用于不透明部分(以防万一您的某些颜色很清晰)