Cocoa - finding out when an NSTabView has changed its tabs
-
26-05-2021 - |
Question
How can I find out when a NSTabViewItem has been changed, i.e. a user has changed the view of an NSTabView?
Ideally I want to generate a notification but any solution would be welcome.
Solution
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
).
A probably smarter solution is to use a delegate. Implement tabView:didSelectTabViewItem:
in the relevant controller.
Docs here.
OTHER TIPS
Here is an example in Swift 3.
Create a custom class for your NSTabViewController
which acts as delegate of NSTabView
. The NSTabViewController
class already implements the NSTabViewDelegate
protocol.
class CustomTabViewController: NSTabViewController {
override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
let identifier = tabViewItem?.identifier as? String
print(identifier)
}
}
Then in Interface Builder:
- Assign the custom class you created to your Tab View Controller in the Identity Inspector in the right panel
- 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
You can also implement other methods in your delegate as explained in the documentation of NSTabViewDelegate
.