视图是否可以在不激活其窗口的情况下接收单击事件,由控制
acceptsFirstMouse(for:)
方法当按钮样式为
.plain
,按钮不再由支持
NSButton
谁的
acceptsFirstMouse
方法会返回
true
),所以你不能独自“点击”按钮。
你可以包装
NSViewRepresentable
围绕按钮,并覆盖
接受第一个鼠标
返回true。
这是来自的代码
this blog post
extension SwiftUI.View {
public func acceptClickThrough() -> some View {
ClickThroughBackdrop(self)
}
}
fileprivate struct ClickThroughBackdrop<Content: SwiftUI.View>: NSViewRepresentable {
final class Backdrop: NSHostingView<Content> {
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
return true
}
}
let content: Content
init(_ content: Content) {
self.content = content
}
func makeNSView(context: Context) -> Backdrop {
let backdrop = Backdrop(rootView: content)
backdrop.translatesAutoresizingMaskIntoConstraints = false
return backdrop
}
func updateNSView(_ nsView: Backdrop, context: Context) {
nsView.rootView = content
}
}
示例用法:
Button("Foo") {
print("triggered")
}
.buttonStyle(.plain)
.acceptClickThrough()