在使用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)雅的方案,評論區(qū)留言