Swift NSToolbar Sample Code
Created By: Debasis Das (2-May-2015)
In this Sample Application we will create a Cocoa Application for Swift NSToolbar Sample Code
We have implemented the NSToolbarDelegate in the AppDelegate of the application
// AppDelegate.swift // Swift-NSToolBar // Created by Debasis Das on 5/1/15. // Copyright (c) 2015 Knowstack. All rights reserved. import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate,NSToolbarDelegate { @IBOutlet weak var window: NSWindow! var toolbar:NSToolbar! var toolbarTabsArray = [] var toolbarTabsIdentifierArray:[String] = [] var currentViewController:NSViewController! var currentView = "" func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application self.toolbarTabsArray = toolbarItems() println(self.toolbarTabsArray) for dictionary in toolbarTabsArray{ toolbarTabsIdentifierArray.append(dictionary["identifier"] as! String) } println(toolbarTabsIdentifierArray) toolbar = NSToolbar(identifier:"ScreenNameToolbarIdentifier") toolbar.allowsUserCustomization = true toolbar.delegate = self self.window?.toolbar = toolbar } func toolbar(toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: String, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { var infoDictionary: Dictionary<String, String> = Dictionary<String, String> () for dictionary in toolbarTabsArray{ if (dictionary["identifier"] as! String == itemIdentifier ){ infoDictionary = dictionary as! Dictionary<String, String> break } } var iconImage = NSImage(named: infoDictionary["icon"]!) let toolbarItem = NSToolbarItem(itemIdentifier: itemIdentifier) toolbarItem.label = infoDictionary["title"]! toolbarItem.image = iconImage toolbarItem.target = self toolbarItem.action = Selector("viewSelected:") return toolbarItem } func toolbarDefaultItemIdentifiers(toolbar: NSToolbar) -> [AnyObject] { return self.toolbarTabsIdentifierArray; } func toolbarAllowedItemIdentifiers(toolbar: NSToolbar) -> [AnyObject] { return self.toolbarDefaultItemIdentifiers(toolbar) } func toolbarSelectableItemIdentifiers(toolbar: NSToolbar) -> [AnyObject] { return self.toolbarDefaultItemIdentifiers(toolbar) } func toolbarWillAddItem(notification: NSNotification) { println("toolbarWillAddItem") } func toolbarDidRemoveItem(notification: NSNotification) { println("toolbarDidRemoveItem") } @IBAction func viewSelected(sender: NSToolbarItem){ println("view is selected") loadViewWithIdentifier(sender.itemIdentifier, withAnimation: true) } func loadViewWithIdentifier(viewTabIdentifier: String, withAnimation shouldAnimate:Bool){ println("loadViewWithIdentifier") println(viewTabIdentifier) if (currentView == viewTabIdentifier){ return } currentView = viewTabIdentifier var infoDictionary: Dictionary<String, String> = Dictionary<String, String> () for dictionary in toolbarTabsArray{ if (dictionary["identifier"] as! String == viewTabIdentifier ){ infoDictionary = dictionary as! Dictionary<String, String> break } } var className = infoDictionary["class"]! println(className) if (className == "DepartmentViewController"){ currentViewController = DepartmentViewController(nibName: "DepartmentView", bundle: nil) } else if (className == "AccountViewController"){ currentViewController = AccountViewController(nibName: "AccountView", bundle: nil) } else if (className == "EmployeeViewController"){ currentViewController = EmployeeViewController(nibName: "EmployeeView", bundle: nil) } println(currentViewController) let newView = currentViewController.view var windowRect = self.window?.frame var currentViewRect = newView.frame println(windowRect) window?.contentView = newView var yPos = windowRect!.origin.y + (windowRect!.size.height - currentViewRect.size.height) let newFrame = NSMakeRect(windowRect!.origin.x, yPos, currentViewRect.size.width, currentViewRect.size.height) window?.setFrame(newFrame, display: true, animate: true) } func toolbarItems() -> NSArray{ var toolbarItemsArray = [ ["title":"Find Departments","icon":"NSPreferencesGeneral","class":"DepartmentViewController","identifier":"DepartmentViewController"], ["title":"Find Accounts","icon":"NSFontPanel","class":"AccountViewController","identifier":"AccountViewController"], ["title":"Find Employees","icon":"NSAdvanced","class":"EmployeeViewController","identifier":"EmployeeViewController"]]; return toolbarItemsArray; } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
View Controllers for each NSToolbarItem
// DepartmentViewController.swift // Swift-NSToolBar // Created by Debasis Das on 5/2/15. // Copyright (c) 2015 Knowstack. All rights reserved. import Cocoa class DepartmentViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } } class AccountViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } } class EmployeeViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
You can download the code from here Swift-NSToolBar
Thanks for the swift toolbar example. I noticed that, on program opening, none of the toolbar items are selected.
How would one programmatically select an item so that a button is selected at program opening?
Thanks.
The below method is called when a NSToolbarItem is called. You can call the viewSelected method by passing a NSToolbarItem as an input parameter.
You can call this method from awakeFromNib or viewDidLoad.
@IBAction func viewSelected(sender: NSToolbarItem){
println(“view is selected”)
loadViewWithIdentifier(sender.itemIdentifier, withAnimation: true)
}
Please let me know if you are not able to do this and I can attach the modified sample application
Regards
Debasis
Thanks for your prompt reply.
I am porting a program over to Swift from Objective-C. The problem I am encountering is that there does not appear to be a function in Swift comparable to NSToolbar’s “setSelectedItemIdentifier” which allows you to programmatically pre-set (i.e., before user input) a particular tool bar item, as there is in Objective-C.
Here is my code in Objective-C, called from the applicationDidFinishLaunching function:
[mainTabView selectTabViewItemAtIndex:1];
[mainToolbar setSelectedItemIdentifier:@”Patients”];
Here is my current code in Swift, called from the windowDidLoad function:
mainTabView.selectTabViewItemAtIndex(1)
?
And here is the function I use that does select the toolbar item and the proper view, when that toolbar item is clicked on by the user:
@IBAction func showPatientListView(sender: NSToolbarItem) {
mainTabView.selectTabViewItemAtIndex(1)
}
However, as far as I can determine, there does not seem to be a function in Swift, comparable to the ‘setSelectedItemIdentifier’ function for the toolbar.
Perhaps I’m missing something, but does the code you provide actually programmatically pre-set a particular toolbar item so that when the user opens the program, an item is already selected?
Oh, my!
In answering your response, I figure out what I need. I’ll post it here in case others have similar issues.
To replace this code in Objective-C:
[mainToolbar setSelectedItemIdentifier:@”Patients”];
use this in Swift:
mainToolbar.selectedItemIdentifier = “Patients”
Thanks very much for your help, and I will continue to follow your web site since I am enjoying and find useful the code samples you are presenting.
KA
thanks for the feedback. I am glad that you find this useful
I tried with the above code in xcode10.2.1 ,where i always get the toolbar delegate as always nil..could you help with this?
error mssg: ERROR: invalid delegate (does not implement all required methods), and so can not be used! (To debug, add a breakpoint to NSToolbarError)