Is it possible for a mouse onHover
event with Mac Catalyst using SwiftUI?
onHover(perform:) is only available for macOS
now.
Is it possible for a mouse onHover
event with Mac Catalyst using SwiftUI?
onHover(perform:) is only available for macOS
now.
Here's a clean solution for Catalyst, but this might be coming soon in iPadOS/Catalyst 13.4. Use the same in any case:
someView.onHover2 { doSomething(isHovering: $0) }
Code to support this:
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
}
}
}
}
class SomeOfMyView: UIView {
// 1. Make sure you save default color upon init
var color: UIColor?
required init?(coder: NSCoder) {
super.init(coder: coder)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
if #available(iOS 13.0, *) {
// 2. add hover gesture
let hover = UIHoverGestureRecognizer(target: self, action: #selector(self.hovering(_:)))
self.addGestureRecognizer(hover)
// 3. saving default color
self.color = self.backgroundColor
}
}
}
@available(iOS 13.0, *)
@objc func hovering(_ recognizer: UIHoverGestureRecognizer) {
// 4. upon hover we change color.
switch recognizer.state {
case .began, .changed:
backgroundColor = .lightGray
case .ended:
backgroundColor = color
default:
backgroundColor = color
}
}
© 2022 - 2024 — McMap. All rights reserved.