osx - Implementing NSSegmentedControl in NSToolbar to control NSTabViewController -
in macos application, i'm trying replicate photos.app implementation of nssegmentedcontrol
in nstoolbar
control nstabviewcontroller
. reference, here's looks like:
so, approach follows:
- hide default
nstabview
header using interface builder - programmatically add
nstoolbar
- insert
nssegmentedcontrol
nstoolbaritem
. - use
#selector
listen changesnssegmentedcontrol
.
here's current implementation:
class windowcontroller: nswindowcontroller, nstoolbardelegate { // mark: - identifiers let maintoolbaridentifier = nstoolbar.identifier("main_toolbar") let segmentedcontrolidentifier = nstoolbaritem.identifier("main_tabbar") // mark: - properties var tabbar: nssegmentedcontrol? = nssegmentedcontrol(labels: ["one", "two"], trackingmode: nssegmentedcontrol.switchtracking.selectone, target: self, action: #selector(didswitchtabs)) var toolbar: nstoolbar? var tabbarcontroller: nstabviewcontroller? // mark: - life cycle override func windowdidload() { super.windowdidload() self.toolbar = nstoolbar(identifier: maintoolbaridentifier) self.toolbar?.allowsusercustomization = false self.toolbar?.delegate = self self.tabbar?.setselected(true, forsegment: 0) self.tabbarcontroller = self.window?.contentviewcontroller as? nstabviewcontroller self.tabbarcontroller?.selectedtabviewitemindex = 0 self.window?.toolbar = self.toolbar } // mark: - nstoolbardelegate public func toolbar(_ toolbar: nstoolbar, itemforitemidentifier itemidentifier: nstoolbaritem.identifier, willbeinsertedintotoolbar flag: bool) -> nstoolbaritem? { var toolbaritem: nstoolbaritem switch itemidentifier { case segmentedcontrolidentifier: toolbaritem = nstoolbaritem(itemidentifier: segmentedcontrolidentifier) toolbaritem.view = self.tabbar case nstoolbaritem.identifier.flexiblespace: toolbaritem = nstoolbaritem(itemidentifier: itemidentifier) default: fatalerror() } return toolbaritem } public func toolbaralloweditemidentifiers(_ toolbar: nstoolbar) -> [nstoolbaritem.identifier] { return [segmentedcontrolidentifier, nstoolbaritem.identifier.flexiblespace] } public func toolbardefaultitemidentifiers(_ toolbar: nstoolbar) -> [nstoolbaritem.identifier] { return [nstoolbaritem.identifier.flexiblespace, segmentedcontrolidentifier, nstoolbaritem.identifier.flexiblespace] } // mark: - selectors @objc func didswitchtabs(sender: any) { let segmentedcontrol = sender as! nssegmentedcontrol if (segmentedcontrol.selectedsegment == 0) { self.tabbarcontroller?.selectedtabviewitemindex = 0 } else if (segmentedcontrol.selectedsegment == 1) { self.tabbarcontroller?.selectedtabviewitemindex = 1 } } }
and, here in action:
now, new macos development , feels it's complicated , convoluted way of solving problem. there easier way achieve same thing ? perhaps somehow in interface builder ? done improve here ? have done wrong ?
thanks time.
Comments
Post a Comment