Search code examples
swiftxcodemacoscocoanstabview

How to set the identifier of an NSTabViewItem?


I want to know when a NSTabView switched to a particular view. For that I've extended NSTabViewController with my custom class to be able to act as delegate:

class OptionsTabViewController: NSTabViewController {
    override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
        print(tabViewItem!.identifier)
    }
}

This prints what looks like pointer memory positions:

Optional(0x608000100e10)
Optional(0x6080000c36b0)

I imagine it should be possible to set those identifiers somewhere in interface builder, but I've tried writing stuff in different text fields labeled as identifier and still get those memory position values in the console.

I've also used print(tabViewItem!.label) but it prints the label in the tab button.

So how can I set that identifier to be able to recognise which view is active in the tab view component?


Solution

  • First of all, you may define your identifier(s) in this way:

    enter image description here

    then in your code you might define an enum for checking which is the current selected tab, doing something like:

    enum YourTabs:String {
       case tab1
       case tab2
       case none
    }
    
    class ViewController: NSViewController, NSTabViewDelegate {
        @IBOutlet var tabView:NSTabView!
    
        public func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
            if let identifier = tabViewItem?.identifier as? String,
                let currentTab = YourTabs(rawValue: identifier) {
                switch currentTab {
                case .tab1:
                    print("do something with tab1")
                    break
                case .tab2:
                    print("do something with tab2")
                    break
                default:
                    break
                }
            }
        }
    }