简体   繁体   English

Cocoa - 找出 NSTabView 何时更改其选项卡

[英]Cocoa - finding out when an NSTabView has changed its tabs

How can I find out when a NSTabViewItem has been changed, ie a user has changed the view of an NSTabView?我怎样才能知道 NSTabViewItem 何时被改变,即用户改变了 NSTabView 的视图?

Ideally I want to generate a notification but any solution would be welcome.理想情况下,我想生成通知,但欢迎任何解决方案。

My original answer suggested to observe selectedTabViewItem of NSTabView , but that doesn't seem to work (on testing I can only get it to observe NSKeyValueObservingOptionInitial ).我原来的答复建议观察selectedTabViewItemNSTabView ,但似乎并没有工作(在测试我只可以得到它,观察它NSKeyValueObservingOptionInitial )。

A probably smarter solution is to use a delegate.一个可能更聪明的解决方案是使用委托。 Implement tabView:didSelectTabViewItem: in the relevant controller.在相关控制器中实现tabView:didSelectTabViewItem:

Docs here .文档在这里

Here is an example in Swift 3.这是 Swift 3 中的一个例子。

Create a custom class for your NSTabViewController which acts as delegate of NSTabView .为您的NSTabViewController创建一个自定义类,它充当NSTabView委托。 The NSTabViewController class already implements the NSTabViewDelegate protocol. NSTabViewController类已经实现了NSTabViewDelegate协议。

class CustomTabViewController: NSTabViewController {
    override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
        let identifier = tabViewItem?.identifier as? String
        print(identifier)
    }

}

Then in Interface Builder:然后在界面生成器中:

  1. Assign the custom class you created to your Tab View Controller in the Identity Inspector in the right panel将您创建的自定义类分配给右侧面板中 Identity Inspector 中的 Tab View Controller
  2. In the interface hierarchy panel on the left, control drag from the Tab View to the Custom Tab View Controller (the name will depend on your custom class) and select delegate from the little popover that appears在左侧的界面层次面板中,控制从 Tab View 拖动到 Custom Tab View Controller(名称将取决于您的自定义类)并从出现的小弹出窗口中选择delegate

You can also implement other methods in your delegate as explained in the documentation of NSTabViewDelegate .您还可以在您的委托中实现其他方法, NSTabViewDelegate 文档NSTabViewDelegate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM