macOS Controls Tutorial: Part 1/2
Learn how to use common macOS UI controls like NSTextField, NSComboBox, NSButton, and more in this two-part series — updated for Xcode 11.3 and Swift 5! By Roberto Machorro.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
macOS Controls Tutorial: Part 1/2
35 mins
- Getting Started with macOS Controls
- NSControl – The Building Block of MacOS Controls
- Set the Value of macOS Controls
- Enable & Disable macOS Controls
- Field of Dreams – NSTextField
- Living in the Past – A Past Tense Verb
- The Value Combo – NSComboBox
- Method 1 – Calling Methods Directly On The Control
- Method 2 – Using A Data Source
- Which Method To Use?
- The Singles Bar – A Singular Noun
- Pop Goes the Weasel – NSPopupButton
- Filling the Spaces – Adding Items To Pop Up Buttons
- The More the Merrier – A Plural Noun
- Text is Next – NSTextView
- The Phrase that Pays – Adding a Text View
- Pushing Your Buttons – NSButton
- Buttoning Things Down – Adding a Button
- Where to Go From Here?
Pushing Your Buttons – NSButton
Buttons are macOS controls designed to send a message to the app whenever they’re clicked.
The control responsible for this on macOS is NSButton.
There are many different styles of buttons (you can view them in Interface Builder’s Object Library). They all work in much the same way, the only difference being their visual representation.
You should use the style of button that best suits your application’s design – refer to the macOS Human Interface Guidelines for advice and guidance on best design practices for your app.
Typically, when working with a button, you’ll simply need to associate an action with the button and set its title. However, there may be times when you need to disable the button, or change its appearance. The following methods allow you to perform those actions:
// disable a button
myButton.isEnabled = false
// enable a button
myButton.isEnabled = true
// getting & setting a button's title
let theTitle = myButton.title
myButton.title = theTitle
// getting & setting a button's image
let theImage = myButton.image
myButton.image = theImage
Looks fairly simple – adding a button to your app in the next section should be a breeze.
Buttoning Things Down – Adding a Button
Open Main.storyboard. Find the Push Button in the Object Library palette and drag it onto the content view. Double-click on it to change its title to Go! :
This time you don’t need to create an outlet for the button. However, you do need to create an action and associate it with the button, so that your app knows when the button has been clicked! :]
Open the Assistant Editor and Ctrl+Drag from the button to the ViewController
implementation.
In the popup window that appears, make sure that the connection is set to Action. Name the action goButtonClicked.
Whenever the user clicks on the button the action method goButtonClicked()
will be called. For now you’ll add some debug code, just to make sure everything’s working.
Open ViewController.swift and add the following code inside goButtonClicked()
:
let pastTenseVerb = pastTenseVerbTextField.stringValue
let singularNoun = singularNounCombo.stringValue
let pluralNoun = pluralNouns[pluralNounPopup.indexOfSelectedItem]
let phrase = phraseTextView.string
let madLibSentence = "A \(singularNoun) \(pastTenseVerb) \(pluralNoun) and said, \(phrase)!"
print("\(madLibSentence)")
This code gets the strings from the text field, the combo box, the popup button and the text view and forms the Mad Lib sentence.
That’s all the code you need for now – build and run your app.
Every time you click the button, you should see a short and silly sentence appear in Xcode’s console.
A dev ate tacos and said: Me coding Mac Apps!!!!
That’s great, but how could you make it even funnier?
How about making your computer read the sentence? Steve Jobs made the first Macintosh say hello to the world in its presentation. You can make your computer talk too… Let’s get at it!
Open ViewController.swift and add this code inside the ViewController
implementation:
// 1
fileprivate enum VoiceRate: Int {
case slow
case normal
case fast
var speed: Float {
switch self {
case .slow:
return 60
case .normal:
return 175;
case .fast:
return 360;
}
}
}
//2
fileprivate let synth = NSSpeechSynthesizer()
First, you declare an enum
to represent the voice rate. Then you create and instance of NSSpeechSynthesizer
which is the class that will convert the text to speech.
Now, add this method inside the ViewController
implementation:
fileprivate func readSentence(_ sentence: String, rate: VoiceRate ) {
synth.rate = rate.speed
synth.stopSpeaking()
synth.startSpeaking(sentence)
}
This method starts the synth
object speaking a string at the determined speed.
Time to call it! Add this code at the end of goButtonClicked()
to read the Mad Libs sentence:
readSentence(madLibSentence, rate: .normal)
Build and run; click Go! and listen to your Mac saying your sentence out loud!
Where to Go From Here?
You can the download the final project containing all the source code from this tutorial up to this point.
In the second part of this tutorial, you’ll learn about more macOS controls, including sliders, date pickers, radio buttons, check boxes and image views – each of which will be added to your Mad Libs application in order to complete it.
In the meantime, if you have any questions or comments about what you’ve done so far, join in the forum discussion below!