DPS923 notes – Thu Jan 12

Welcome. Mac overview (or review). iOS development with Swift and Cocoa.

 

Today’s topic sequence

Overview, or review, of the Mac. Login, using Finder, and using a browser.

Introduction to Xcode, the developer tool. Start Xcode, and create a project.

Hands-on with Swift (the language) and a little bit of Cocoa (the class library and runtime).

In Xcode we will use a feature, known as a “playground”.

We’ll look at Optionals, a topic that we didn’t get to on Monday.

Then, we will create a simple iOS application, a single-view app.

 

Handouts:

Course info sheet

Getting started with Swift

Getting started with Xcode

 

Resources:

Swift Programming Language (Apple, HTML, or for iBooks)

Swift Standard Library Reference (Apple, HTML, PDF)

Xcode Basics (Apple, HTML)

Xcode Application Help (Apple, HTML) (also available on the Xcode ‘Help’ menu)

Xcode Gestures and Keyboard Shortcuts (Apple, HTML)

Xcode Keyboard Shortcuts (McIntyre, PDF)

 

School of ICT computer-lab T3078 with Mac mini systems

The School of ICT has a lab that’s dedicated to iOS programming and web programming, in room T3078.

Read this document for an introduction to the physical environment.

 

Hands-on with macOS

Finder, file system, work drive, navigation

Browser(s), downloads (to desktop)

Cmd+space to use “Spotlight” to find and open any program or document

Cmd+Tab to switch between running apps

Cmd+` (back quote) to switch between windows in a specific app

Using the dock

 

Get familiar with Xcode, the developer tool

From this course’s ‘Resources’ page…

Xcode Overview – HTML – PDF

Xcode Basics Help – HTML

Xcode Application Help (Apple, HTML) (also available on the Xcode ‘Help’ menu)

Xcode Gestures and Keyboard Shortcuts (Apple, HTML)

Xcode Keyboard Shortcuts (McIntyre, PDF)

Oft-used keyboard shortcuts:

Build Cmd+B, Run (with debugging) Cmd+R

Navigator area management – Cmd+0, Cmd+1, Option+Cmd+0

Show/hide debug console area – Shift+Cmd+Y

If you have multiple projects open…

  • Command-` (back quote character, beside the 1 key) – switch window within app
  • Control-down-arrow – show/preview all open windows of the app

 

Optionals in Swift

When you declare a variable or property, you usually assign its type, and you often assign a value.

If you don’t know the initial value, or don’t want one, add ? (question mark) as a type suffix. This marks the variable as optional, where its value may be absent. For example:

// Typical variable
var firstName = "Peter"

// Optional variable
var middleName: String?

 

Read this section from The Swift Programming Guide before continuing.

There are two common ways to access the value of an optional (variable):

  1. Use the bang, or exclamation mark, !
  2. Use an optional binding block of code

 

When you are sure that the variable has a value, you can append a bang to the variable name. For example:

// Assume that "firstName" is an optional string, or String?
print(firstName!)

 

Alternatively, you can create an “optional binding” block of code. For those familiar with the C# “using” block of code, it’s a similar concept. Here’s an example:

// Using the variable "firstName" from above, which is an optional string,
// attempt to create a temporary constant ("let")...

if let fname = firstName {
  print(fname)
} else {
  print("nothing")
}

 

String – number conversions

This is not a very exciting topic. However, it’s very important, because it helps a new iOS programmer make progress.

Try this in a playground:

// Create an Int
var age: Int = 23

// Create a String that can convert to an Int
var ageString: String = "45"

// Attempt to convert the String into an Int
age = Int(ageString) ?? 0

// Remove the ?? (nil-coalescing operator) and see what happens
// Can replace it with a bang ! to unwrap the value (if you know it's there)

// Create a Double
var temp: Double = 24.5

// Create a String that can convert to a Double
var hotDay: String = "35.5"

// Attempt to convert the String into a Double
temp = Double(hotDay) ?? 0.0

// Remove the ?? (nil-coalescing operator) and see what happens
// Can replace it with a bang ! to unwrap the value (if you know it's there)

 

Now, we’ll try the same with an iOS app. Below, you will learn about two user interface controls:

Label – text displayed on a view; cannot be edited by the user

Text field – text displayed on a view; can be edited by the user

The important characteristic of both controls is that they work with “text”, specifically a String object. Therefore, when we need to display a number, or get numeric input, we need to do a string-to-number conversion.

 

Brief MVC introduction

As introduced in the CCC “Model-View-Controller” document:

The Model-View-Controller (MVC) design pattern assigns objects in an application one of three roles: model, view, or controller. …

Each of the three types of objects is separated from the others by abstract boundaries and communicates with objects of the other types across those boundaries. The collection of objects of a certain MVC type in an application is sometimes referred to as a layer—for example, model layer.

MVC is central to a good design for a Cocoa application. The benefits of adopting this pattern are numerous. Many objects in these applications tend to be more reusable, and their interfaces tend to be better defined. Applications having an MVC design are also more easily extensible than other applications.

Moreover, many Cocoa technologies and architectures are based on MVC and require that your custom objects play one of the MVC roles.

 

Controllers

In the simple apps that we have worked with, there has been one controller class, named “ViewController”. It is in a source code file named “ViewController.swift”. There’s nothing magical or prescriptive about these names – the ‘new project’ template simply created them that way.

It should be apparent that an app can have many controllers.

When you begin creating your own controllers, we strongly recommend that you use meaningful names. For example, the controller for a list of teacher names should be called something like “TeacherList”.

Views

In the simple apps, there has been one view, also known as a “scene” on the “storyboard”.

It should also be apparent that the storyboard can hold many scenes. The storyboard itself is a source code file, and XML is the language. It includes a collection of <scene> elements (although our simple app has only one <scene> element).

Each scene has an internal “object identifier” (which is a string). How can you show this data? Select the “View Controller” icon on the scene’s dock. Show the Identity Inspector. In the “Document” area, you will see a value for “Object ID”. Well, that’s not a very friendly name. Use the “Label” field to enter a better and friendlier identifier.

Model

Our simple apps may not have a model object. We’ll get to this topic in the next week or two.

 

Getting started – create a Convert project

In Xcode, create a new project:

Template is “Single View Application”

(Next…)

Product Name is “Convert”
Organization Name is Seneca College
Organization Identifier is ca.senecacollege.ict

Language is Swift

Devices is iPhone

Un-check (clear) all three checkboxes on this panel

(Next…)

Choose the folder to save your work in, USB or the Work Drive

Un-check (clear) the Create Git repository… checkbox

 

Select (to display) the Main.storyboard. It will show you the scene that’s managed by the view controller class.

At the bottom of the Utility area, select the Object library. From that library, locate and add these items to the upper-left area of the scene:

  • Label (to simply display an app title to the user)
  • Text Field (allows the user to enter a number with decimal places; change its Keyboard Type to Numbers and Punctuation)
  • Button (to start the ‘convert’ action)
  • Label (displays the result)

Click the Show Document Outline button. Select/highlight the View object.

Click the Resolve Auto Layout Issues button. In the lower “All Views” area, select Add Missing Constraints.

If you wish to preview what it will look like on an iPhone:

Show the Assistant Editor. On its jump bar, click the Automatic segment, and change (select) Preview. When you’re happy, you can close (hide) the Assistant Editor.

Create outlets for the Text Field and the bottom Label.

Your teacher will show you how to do this.

Create an action for the Button, using the code guidelines below.

How to dismiss the keyboard? Call the resignFirstResponder() method on the text field.

 

String to number

A user will enter a number into the text field. The number could include a decimal portion. In the text field, the data is a string. Therefore, we must convert the string data to a number.

Use a the Double() initializer:

// String to double
// Assume the name of the text field is “userInput”
var input = Double(userInput.text!)!

// Perform an arithmetic operation
input = (input * 2) + 3.45214

 

Number to string

The label has a text property, which needs a string. Therefore, we must convert the number data to a string.

Use the String() initializer:

// double to String
results.text = String(format: “%1.3f”, input)

 

Begin working with iOS apps, and essential user interaction

In Xcode, create another new project; its name will be “January12”.

Study the project’s structure, it has three new source code assets:

  1. AppDelegate – handles app lifecycle events (launch, interrupt because of incoming phone call, etc.), and app state transitions (e.g. active, background, etc.)
  2. Main.storyboard – container that holds the app’s scenes (i.e. the user interface)
  3. ViewController – manages one scene (view)

Learn more about the AppDelegate in this introduction. The “Overview” section of the UIApplication Class Reference document is good. Also, the “Overview” section of the UIApplicationDelegate Protocol Reference document is good.

Learn more about the storyboard in this introduction.

Learn more about a controller in this introduction. The “Overview” section of the UIViewController Class Reference document is good.

Run (Command+R), and the iOS Simulator will open your app.

While using the iOS Simulator app:

  • Shift+Command+H = performs a “home” button press
  • Command+Q = quit the simulator app
  • Command+K = show/hide the keyboard on the simulator
  • Command+3 = scale window to the smallest size
  • Command+2 = scale window a bit larger

Look at the iOS Simulator app’s menus to learn more about what it can do for you.

Click/select Main.storyboard, and the app’s scene will load in the editor. Look at the right-side Utility area, and notice the Attributes Inspector (fourth icon from left).

At the bottom of the Utility area, notice the Object library (third icon from left). That list shows the user interface objects that can be dragged to a scene.

We will work with these three objects as you begin work on the first assignment in the course, “Assign 1”.

In Xcode, the screen layout when designing the app’s user interface shows these areas:

  1. Left-side Navigator area – show or hide, you decide (Command+0)
  2. Storyboard, select (click) the scene (view) that you want to work with (then select the first icon in its dock, named “View Controller”
  3. Then press Option+Command+Return to open the Assistant Editor, which shows the scene’s controller
  4. Right-side Utility area – should show that, because we’ll need it (toggle with Option+Command+0)

How do you get programmatic access to objects in the user interface? Two important ways for new iOS programmers are to use outlets and actions. (A third way, which you will use soon, is known as a delegate.)

What is… an outlet, and an action?

  • Outlet – an object (in your class) that points to a user interface object
  • Action – the method that’s called when an event occurs (e.g. value changed, button tap, etc.)

Creating an outlet or action for a user interface object:

Click to select / highlight a user interface object. Then:

  1. Press and hold the Control key
  2. Click and drag to the source code, until the insertion pointer appears, then release the mouse button (or touchpad)
  3. Complete the configuration of the dialog that pops up

The “Name” field is for the outlet or action name that appears in your source code. The name should begin with a lowercase letter. Multi-word names begin with a lowercase letter, but use camel-casing for the remaining words (e.g. userInput, or doSomething).

The following shows the dialog for an outlet (text field), and for an action (button). Click to view them full-size in a new tab/window.

Outlet, create, for text field

 

Action, create, for button

Tip: When configuring an action, set the Type to the actual type of the user interface control.

 

Learn the common user interface controls

Create an iOS app, using the Single View Application template.

Select Main.storyboard to edit the user interface.

 

Text field

“Text fields allows the user to input a single line of text into an app. You typically use text fields to gather small amounts of text from the user and perform some immediate action, such as a search operation, based on that text.” (Text Fields, from the UIKit User Interface Catalog)

Drag a text field to the scene.

Size to fit your situation.

Create an outlet. For the code samples below, we’ll assume that its name is “userInput”.

Read the content from the “text” property with this code:

var foo = userInput.text

Write the content to the “text” property with this code:

userInput.text = “hello”

Study/skim the UITextField class reference documentation.

 

Label

“A label displays static text. Labels are often used in conjunction with controls to describe their intended purpose, such as explaining which value a button or slider affects.” (Labels, from the UIKit User Interface Catalog)

Drag a label to the scene.

Size to fit your situation.

Create an outlet. For the code samples below, we’ll assume that its name is “results”.

Read the content from the “text” property with this code:

var foo = results.text

Write the content to the “text” property with this code:

results.text = “hello”

Study/skim the UILabel class reference documentation.

 

Button

“Buttons let a user initiate behavior with a tap. You communicate a button’s function through a textual label or with an image.” (Buttons, from the UIKit User Interface Catalog)

Drag a button to the scene.

Size to fit your situation.

Create an action. For the code samples below, we’ll assume that its name is “doSomething”.

Write code in the method implementation to do whatever you want. For example, copy from the text field to the label:

results.text = userInput.text

Study/skim the UIButton class reference documentation.

 

Text view

“A text view accepts and displays multiple lines of text. Text views support scrolling and text editing. You typically use a text view to display a large amount of text, such as the body of an email message.” (Text Views, from the UIKit User Interface Catalog)

Drag a text view to the scene.

In this example, we will use the text view to display content, but editing will be disabled. In the Attributes Inspector, you can type or paste text. (The code example has the text from the DPS923 course description.)

Size it to fit your situation.

Create an outlet. For the code samples below, we’ll assume that its name is “courseDescription”.

Read the content from the “text” property with this code:

var foo = courseDescription.text

Write the content to the “text” property with this code:

courseDescription.text = “hello”

Study/skim the UITextView class reference documentation.

 

Segmented control

“A segmented control is a horizontal control made of multiple segments, each segment functioning as a discrete button.” (Segmented Controls, from the UIKit User Interface Catalog)

Drag a segmented control to the scene.

Size to fit your situation.

Create an outlet, if you want access to the segmented control’s properties and methods anywhere in the controller. For the code samples below, we’ll assume that its name is “itemSelector”.

Create an action, if you want to handle an event, such as a change in the selected segment. For this control, the “Value Changed” event is the default event shown in the dialog, but you can choose another if you wish. (Remember to change the Type selected to UISegmentedControl.) For the code samples below, we’ll assume that its name is “itemSelectionChanged”.

Read the control state with this code, from anywhere in the controller:

var segmentIndex = itemSelector.selectedSegmentIndex
var segmentTitle = itemSelector.titleForSegmentAtIndex(2)

Write the control state with this code, from anywhere in the controller:

itemSelector.selectedSegmentIndex = -1
itemSelector.setEnabled(false, forSegmentAtIndex: 2)
itemSelector.setTitle(“Hello” forSegmentAtIndex: 1)

Handle an event in the ‘action’ method, with this code: (“sender” is a reference to the segmented control)

// do whatever; you can use “sender” as the local name of the control
var segmentIndex = sender.selectedSegmentIndex
sender.setTitle(“Hello” forSegmentAtIndex: 1)

Study/skim the UISegmentedControl class reference documentation.

 

Slider

“Sliders enable users to interactively modify some adjustable value in an app, such as speaker volume or screen brightness. Users control a slider by moving its current value indicator along a continuous range of values between a specified minimum and maximum.” (Sliders, from the UIKit User Interface Catalog)

Drag a slider to the scene.

Size to fit your situation. Configure its minimum and maximum values, and its initial value.

Create an outlet, if you want access to the slider’s properties and methods anywhere in the controller. For the code samples below, we’ll assume that its name is “temperature”.

Create an action, if you want to handle an event, such as a change in the slider’s current value indicator. For this control, the “Value Changed” event is the default event shown in the dialog, but you can choose another if you wish. (Remember to change the Type selected to UISlider.) For the code samples below, we’ll assume that its name is “temperatureChanged”.

Read the control state with this code, from anywhere in the controller:

var temperatureValue = self.temperature.value
var maxTemperature = self.temperature.maximumValue

Write the control state with this code, from anywhere in the controller:

temperature.value = 23.5f;

Handle an event in the ‘action’ method, with this code: (“sender” is a reference to the slider)

// do whatever; you can use “sender” as the local name of the control
var newTemperature = sender.value
sender.value = 31.0f;

Study/skim the UISlider class reference documentation.

 

Switch

“A switch lets the user turn an option on and off. You see switches used throughout the Settings app to let a user quickly toggle a specific setting.” (Switches, from the UIKit User Interface Catalog)

 – 

Drag a switch to the scene.

Create an outlet, if you want access to the switch’s properties and methods anywhere in the controller. For the code samples below, we’ll assume that its name is “activateAudio”.

Create an action, if you want to handle an event, such as a change in the switch’s state. For this control, the “Value Changed” event is the default event shown on the dialog, but you can choose another if you wish. (Remember to change the Type selected to UISwitch.) For the code samples below, we’ll assume that its name is “switchTapped”.

Read the control state with this code, from anywhere in the controller:

var isAudioActivated = activateAudio.on

Write the control state with this code, from anywhere in the controller:

activateAudio.on = true

Handle an event in the ‘action’ method, with this code: (“sender” is a reference to the switch)

// do whatever; you can use “sender” as the local name of the control
if (sender.on)…

Study/skim the UISwitch class reference documentation.

 

Stepper

“A stepper lets the user adjust a value by increasing and decreasing it in small steps. Steppers are used in situations where a user needs to adjust a value by a small amount.” (Steppers, from the UIKit User Interface Catalog)

Drag a stepper to the scene.

Configure its minimum, maximum, and current values, and other properties if you wish.

Create an outlet, if you want access to the stepper’s properties and methods anywhere in the controller. For the code samples below, we’ll assume that its name is “ageSelector”.

Create an action, if you want to handle an event, such as a change in the stepper’s state. For this control, the “Value Changed” event is the default event shown on the dialog, but you can choose another if you wish. (Remember to change the Type selected to UIStepper.) For the code samples below, we’ll assume that its name is “adjustAge”.

Read the control state with this code, from anywhere in the controller:

var currentValue = ageSelector.value
var maximumValue = ageSelector.maximumValue

Write the control state with this code, from anywhere in the controller:

ageSelector.Value = 25.0f

Handle an event in the ‘action’ method, with this code: (“sender” is a reference to the stepper)

if (sender.value > 29)…

Study/skim the UIStepper class reference documentation.

 

Image

“An image view displays an image or an animated sequence of images. An image view lets you efficiently draw an image (such as a JPEG or PNG file) or an animated series of images onscreen, scaling the images automatically to fit within the current size of the view.” (Image Views, from the UIKit User Interface Catalog)

If you have an existing image, save it somewhere in your project. In Project Navigator, you should probably create a folder to hold your app’s image assets. Maybe create a new group (folder) named “Images” under your main project group (folder), or under the Supporting Files group (folder). Then right-click then “Add Files to…” (and make sure to check-mark/select “Copy items into destination…).

When you do this, then the images are available to your Media library (fourth icon from the left) in the panel at the bottom of the Utility area (on the right side of the Xcode screen). Simply drag-and-drop the image to your scene. That action will wrap your image with a UIImage object, which you can then configure to suit your needs.

Alternatively, you can set the image at runtime.

Create an outlet. For the code samples below, we’ll assume that its name is “myPhoto”.

Read the content from the “image” property with this code:

CGSize imageSize = myPhoto.image.size()

Write the content to the “image” property with this code:

myPhoto.image = UIImage.imageNamed(“peter.png”)

Study/skim the UIImageView class reference documentation.

 

Code example

A code example will also be posted in the GitHub code repository.

Here’s the startup state of the app:

UI Controls startup state

 

Here’s what it looks like after being used:

UI Controls after using

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Advertisements
%d bloggers like this: