Simple Modal Alerts
To display a modal sheet alert with a message:
let alert: NSAlert = NSAlert()
alert.messageText = "An error occurred in your last action:"
alert.informativeText = message
alert.alertStyle = NSAlertStyle.critical
alert.addButton(withTitle: "OK")
alert.beginSheetModal(for: window, completionHandler: nil)
To display a modal window alert with a message:
let alert: NSAlert = NSAlert()
alert.messageText = "An error occurred in your last action:"
alert.informativeText = message
alert.alertStyle = NSAlertStyle.critical
alert.addButton(withTitle: "OK")
alert.runModal()
Text Boxes
Setting plain text in a text box:
textBox.stringValue = theString
Taking a plain NSString and inserting it as attributed text into a text box:
let attr = NSAttributedString(string: theString as String)
textBox.textStorage?.append(attr)
Radio Buttons
To group, Control-drag to make an Action for the first button in the group. Strongly type this to an NSButton sender, with a function name for the group as a whole. Then Control-drag others in the group to the same Action.
For each button in the group, edit its Tag attribute to a different number (1, 2, …) so that each has a tag which is unique within that group.
Edit group Action to the likes of
@IBAction func filterRadioButton(_ sender: NSButton) {
selectedFilterButton = sender.tag
}
where
var selectedFilterButton = 1
to contain the tag number of the currently selected button in the group.
You can then test which of the buttons in a group is selected using
if (selectedFilterButton == 1)
Add each button as an individual Outlet, and you can then set the selected button using
filterTMbutton.state = NSOnState
Popup Menus
Setting a popup menu up from a list of strings, in viewDidLoad():
let menuItemList = ["sec", "min", "hour", "day"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view - set the popup menu up
popupMenu.removeAllItems() // clean the list of items in the menu first
popupMenu.addItems(withTitles: menuItemList) // add the items
selectedItemTitle = (popupMenu.selectedItem?.title)! // gets the currently selected item
}
then
selectedItemTitle = popupMenu.titleOfSelectedItem! // also gets the currently selected item.
File Save dialog
To display a save dialog and write out a string to the file:
var fileContentToWrite = theOutputString
let FS = NSSavePanel()
FS.canCreateDirectories = true
FS.allowedFileTypes = ["text", "txt"]
FS.begin { result in
if result == NSFileHandlingPanelOKButton {
guard let url = FS.url else { return }
do {
try fileContentToWrite.write(to: url, atomically: false, encoding: String.Encoding.utf8)
} catch {
doErrorAlertSheet(message: error.localizedDescription, window: self.window)
}
}
}
Last tested on Xcode 8.2.1, Swift 3.0.2, macOS Sierra 10.12.3.
