5

请教下大佬们, swiftUI 菜单栏应用 onHover 事件触发问题

 2 years ago
source link: https://www.v2ex.com/t/865223
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  iDev

请教下大佬们, swiftUI 菜单栏应用 onHover 事件触发问题

  storyxc · 11 小时 22 分钟前 · 572 次点击

刚学习 swift 和 swiftUI 不久,目前在试着用 swiftUI 做一个纯菜单栏的 todolist 工具。现在调界面的时候碰到个问题:点击图标弹出应用后,子视图上 TodoRowView 的 onHover 事件无法触发,必须要点击一下弹出的这块区域才可以,请教下这个问题的解决办法,不胜感激🙏

主视图结构大概是

struct HomeView: View {
    var body: some View {
        VStack {
            CustomSegmentedControl()
            
            ScrollView {
                TodoRowView()
                TodoRowView()
                TodoRowView()
            }
            HStack {
                xxxx..
            }
        }
    }
}

问题如下:

out.gif

第 1 条附言  ·  7 小时 38 分钟前

找到一个解决办法,菜单栏popover的代码我是看Kavsoft的视频抄的的,这块是AppKit的代码写的,并没有完全理解。只需要调整下popover.contentViewController?.view.window?.makeKey()这行代码的位置即可,把这行代码从setUpMacMenu中,挪到menuButtonAction的else中,这样还可以解决另一个问题:点击弹出区域外的位置,菜单弹出区域不会自动关闭。

class AppDelegate: NSObject, ObservableObject, NSApplicationDelegate {
    private var statusItem: NSStatusItem?
    private var popover = NSPopover()
    
    func applicationDidFinishLaunching(_ notification: Notification) {
        setUpMacMenu()
    }
    
    func setUpMacMenu() {

        popover.animates = true
        popover.behavior = .transient

        popover.contentViewController = NSViewController()
        popover.contentViewController?.view = NSHostingView(rootView: HomeView())
        
        //popover.contentViewController?.view.window?.makeKey()
        
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        if let menuButton = statusItem?.button {
            menuButton.image = .init(systemSymbolName: "d.circle.fill", accessibilityDescription: nil)
            menuButton.action = #selector(menuButtonAction)
        }
    }
    
    @objc func menuButtonAction() {
        if popover.isShown {
            popover.performClose(nil)
        }else {
            if let menuButton = statusItem?.button {
                popover.show(relativeTo: menuButton.bounds, of: menuButton, preferredEdge: .minY)
                popover.contentViewController?.view.window?.makeKey()
            }
        }
        
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK