ios 如何使用Catalyst实现onHover事件?

zbq4xfa0  于 2023-05-19  发布在  iOS
关注(0)|答案(2)|浏览(156)

使用SwiftUI的Mac Catalyst是否可以使用鼠标onHover事件?
onHover(perform:)目前仅适用于macOS

rkttyhzu

rkttyhzu1#

这里有一个干净的解决方案,但这可能很快就会在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
            }
        }
    }
}
3vpjnl9f

3vpjnl9f2#

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
        }
    }

相关问题