20 Cocoa Apps Challenge

Cocoa

App 01: Hello There!

Getting to know the basics

  • Label, Text Field, and Button Controls
  • Outlets and Actions
  • Constant, String Interpolation, and stringValue Property

Basic Controls

Our simple Cocoa app has three controls:

label
text field
button

Outlets and Actions

The label and the text field are connected as outlets and the button as action

  • The label outlet (named message) displays any values assigned to it
  • The text field outlet (named nameField) captures and displays any values entered into it
  • The button calls the greet action when it gets pressed
Notice that in Cocoa, labels have the type NSTextField and not UILabel

A look at greet in action when it gets called

① Near the top you'll see a couple of @IBOutlet annotations marking message and nameField properties as outlets.

The @IBAction annotation marks the greet function to be the one to be called when the button is pressed.

Constant

② Inside the greet function, the first line of code is a constant declaration named name. The name constant is assigned whatever the value is contained inside nameField text field. Since the property being accessed in nameField is stringValue, the name constant will contain a String type value.

A very important thing to note is that a constant can only ever be assigned a value once. Once a value is set, it can never be changed.

String Interpolation

③ We see the name constant embedded inside a \(), inside a string construct. This is equivalent to: "Hello " + name + "!"

④ The interpolated value is then assigned to the message label outlet's string value which gets promptly displayed.

⑤ Finally, we reset the text field in preparation for the next input by assigning an empty String value.

The stringValue property

NSTextField derives its stringValue property from its superclass NSControl.

stringValue allows you to access a control's value. Access means you can either get or set its value. This property returns the value of type String.

Get

nameField.stringValue is an example of a get access. It just gets the value contained inside it.

Set

message.stringValue = "Hello Arthur!" is an example of set access. It replaces any values currently in it with the new value being assigned to it.

nameField.stringValue = "" is also a set access. In this case, nameField is just assigned an empty String.

How To

Code

//
//  AppDelegate.swift
//  Hello There!
//  Created by Arthur Kho (github.com/islandjoe) on 08/16.
// 
//  MIT License
//  Copyright (c) 2016 Arthur Kho
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var message: NSTextField!
  @IBOutlet weak var nameField: NSTextField!

  @IBAction func greet(sender: NSButton) {

    let name = nameField.stringValue

    message.stringValue = "Hello \(name)!"

    nameField.stringValue = ""
  }
}

20 Cocoa Apps Challenge