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

问题描述 投票:0回答:1

如果我单击顶部或底部附近的矩形,则将创建一个宽度为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 {}也会发生同样的想法-它只是在鼠标悬停在形状框矩形上时触发。

swiftui shapes
1个回答
0
投票

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)
.contentShape(Rectangle().rotation(self.fixture.currentAngle))  // << here !! NB to not put this line after .position()
    .position(x: x, y: y )

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

使用Xcode 11.4 / iOS 13.4测试

注意:请注意,命中测试仅适用于不透明的部分(以防万一您的某些颜色清晰可见)

© www.soinside.com 2019 - 2024. All rights reserved.