Вот чистое решение для Catalyst, но оно может скоро появиться в iPadOS / Catalyst 13.4. Используйте то же самое в любом случае:
someView.onHover2 { doSomething(isHovering: $0) }
Код для поддержки этого:
import SwiftUI
extension View {
func onHover2(perform action: @escaping (Bool) -> Void) -> some View {
return self.overlay(HoverRecognizer(action: action))
}
}
public struct HoverRecognizer: UIViewRepresentable {
var action: (Bool) -> Void
public func makeUIView(context: Context) -> UIView {
return HoverView(action)
}
public func updateUIView(_ uiView: UIView, context: Context) {
}
private class HoverView: UIView {
var action: (Bool) -> Void
init(_ action: @escaping (Bool) -> Void) {
self.action = action
super.init(frame: CGRect.zero)
self.addGestureRecognizer(UIHoverGestureRecognizer(
target: self,
action: #selector(hovering(_:))))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
func hovering(_ recognizer: UIHoverGestureRecognizer) {
switch recognizer.state {
case .began, .changed:
action(true)
case .ended:
action(false)
default:
break
}
}
}
}