SwiftUI MacOS View的.OnHover 鼠標(biāo)懸停問題

在使用SwiftUI 開發(fā) MacOS應(yīng)用時(shí),使用View的.OnHover來更新View樣式時(shí)發(fā)現(xiàn),當(dāng)Window失去焦點(diǎn),再次在該View處點(diǎn)擊Window獲得焦點(diǎn),該View不會(huì)觸發(fā)onHover。

struct DemoView: View {
  @State var isHovering: Bool = false
  var body: some View {
    ZStack(alignment: .topLeading) {
      VStack(alignment: .center, spacing: 8){
          ...
      }
      .frame(width:400)
      .onHover { isHovering in
         self.isHovering = isHovering
      }

      if isHovering {
          // 添加視圖
      }
    }
  }
}

優(yōu)化方案

加入鼠標(biāo)監(jiān)聽視圖層

import AppKit
import SwiftUI

public class MouseMonitorNSView : NSView {
    
    var trackingArea : NSTrackingArea?
    public var onHover: ((Bool) -> Void)?
    
    public override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.clear.cgColor
        
    }
        
    override public func updateTrackingAreas() {
        if let ta = trackingArea {
            self.removeTrackingArea(ta)
        }
        
        if !self.isHidden {
            let opt = (
                NSTrackingArea.Options.mouseEnteredAndExited.rawValue
//                | NSTrackingArea.Options.mouseMoved.rawValue
                | NSTrackingArea.Options.activeAlways.rawValue
            )
            trackingArea = NSTrackingArea(rect: self.bounds, options: NSTrackingArea.Options(rawValue: opt), owner: self, userInfo: nil)
            self.addTrackingArea(trackingArea!)
        }
    }
    
    public override func mouseEntered(with event: NSEvent) {
//        print("mouseEntered")
        if let hoverBlock = onHover {
            hoverBlock(true)
        }
    }
    
    public override func mouseExited(with event: NSEvent) {
//        print("mouseExited")
        if let hoverBlock = onHover {
            hoverBlock(false)
        }
    }
    
//    public override func mouseMoved(with event: NSEvent) {
//        print("mouseMoved")
//    }
//
}

public struct MouseMonitorView : NSViewRepresentable {
    
    private let onHover: (Bool) -> Void
    
    public init(onHover: @escaping (Bool) -> Void){
        self.onHover = onHover
    }
    
    public func makeNSView(context: Context) -> MouseMonitorNSView {
        let view = MouseMonitorNSView()
        view.onHover = onHover
        return view
    }
    
    public func updateNSView(_ nsView: MouseMonitorNSView, context: Context) {
        nsView.onHover = onHover
    }
}

DemoView 改造后

struct DemoView: View {
  @State var isHovering: Bool = false
  var body: some View {
    ZStack(alignment: .topLeading) {
      MouseMonitorView { isHovering in
        self.isHovering = isHovering
      }//此視圖在window失去焦點(diǎn)亦能監(jiān)聽到鼠標(biāo)事件,保持與VStack位置大小一致
      VStack(alignment: .center, spacing: 8){
          ...
      }
      .frame(width:400)
//      .onHover { isHovering in
//         self.isHovering = isHovering
//      }

      if isHovering {
          // 添加視圖
      }
    }
  }
}

此方案有個(gè)小小注意點(diǎn):在window失去焦點(diǎn)時(shí),視圖亦能監(jiān)聽到鼠標(biāo)進(jìn)出事件

后記

是否有更優(yōu)雅的方案,評(píng)論區(qū)留言

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容