【问题标题】:Detect active NSSplitViewItem检测活动的 NSSplitViewItem
【发布时间】:2018-11-16 17:39:51
【问题描述】:

我有一个带有(几个)SplitViewItems 的 SplitView。 Echt SplitViewItem 有一个 ViewController,里面有多个视图。

我需要检测哪些 SplitViewItems 具有用户的焦点。

例如:如果用户单击任何控件/视图(或以任何其他方式导航到它),则包含该视图项的 SplitViewItem 的背景应该改变。由于我不知道 SplitViewItem 中的 ViewController 中将包含哪些/多少视图,所以我更愿意检测哪个 SplitViewItem 是 SplitViewController 中的“活动”视图。

我整天都在寻找解决方案。我找不到任何类型的通知,也找不到解决此管理响应者链的方法。

谁能指出我正确的方向?一个(快速)代码示例将不胜感激。

谢谢!

【问题讨论】:

    标签: swift nssplitview nssplitviewcontroller


    【解决方案1】:

    我花了很多时间研究,但我找到了一个可行的解决方案。不是最优雅的,但可以工作。

    我发现最好的方法是将事件监视器添加到 SplitViewController。

    在 viewDidLoad() 中添加以下代码:

        NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .flagsChanged]) { [unowned self] (theEvent) -> NSEvent? in
            let eventLocation = theEvent.locationInWindow
            let numberOfSplitViews = self.splitViewItems.count
            var activeIndex: Int?
    
            for index in 0..<numberOfSplitViews {
                let view = self.splitViewItems[index].viewController.view
                let locationInView = view.convert(eventLocation, from: nil)
                if ((locationInView.x > 0) && (locationInView.x < view.bounds.maxX) && (locationInView.y > 0) && (locationInView.y < view.bounds.maxY)) {
                    activeIndex = index
                    break
                }
            }
    
            switch theEvent.type {
            case .keyDown:
                print("key down in pane \(activeIndex)")
                self.keyDown(with: theEvent)
            case .leftMouseDown, .rightMouseDown:
                print("mouse down in pane \(activeIndex)")
                self.mouseDown(with: theEvent)
            case .flagsChanged:
                print("flags changed in pane \(activeIndex)")
                self.flagsChanged(with: theEvent)
            default:
                print("captured some unhandled event in pane \(activeIndex)")
            }
            return theEvent
        }
    

    (您可能需要根据自己的喜好调整相关事件。另外,您可能需要使用 NSEvent.removeMonitor(_:) 删除监视器)。

    此外(超出此问题的范围),您可能还需要考虑将变量 activeIndex 设为可观察的类变量(我使用 RxSwift 进行了此操作),让您可以轻松地对“活动窗格”内发生的任何更改做出反应'。

    欢迎任何更优雅/简单的解决方案!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多