Chapter 12 Stack Views

  • In the Main.storyboard, drag a new View Controller from the object library onto the canvas. Drag 4 instances of UILabel onto the canvas and name them Name, Serial, Value, and Date Created.

Content hugging priority – holds the view to a certain size, the higher the priority the lower the tolerance for view size change.

  • Select the Date Created and change the vertical content hugging priority to 249 in the inspector.

When the stack view is selected and the distribution is switched to fill equally the labels are spread equally. For the purposes of the Homepwner leave the distribution on fill.

Stack views are very powerful when is comes to developing the appearance of the application. When you combine stack views you end up with nested stack views that can be used to create may applications.

  • Select Name on the label on the canvas click on the left most button on the Auto Layout constraints menu bar, thus embedding a stack view inside another one.
  • In the attributes inspector change the axis to horizontal.
  • Drag a text field to the right of the label. Open the size inspector for the text field and set its Horizontal Content Compression Resistance Priority to 749.
  • Select the horizontal stack view and open the attributes inspector. Change the spacing to 8pts.
  • Repeat these steps for Serial and Value labels

To align the labels properly:

  • Select the Vertical stack, open the attributes inspector and change the spacing to 8pts.
  • Click on the Data label and centrally align the label
  • Control drag from Name to Serial and select leading, do the same from Serial and Value

Segue – moves another view controller’s view onto the screen. Each segue has a style, action item, and an identifier.

  • Control + drag from the ItemCell prototype to the new view controller and select show
  • Create a new file/class named DetailViewController
  • Opt + click on main.storyboard, click + drag from each text field to the class and name the outlet the proper name, do this for the date label
  • Include the the snippets of code shown below in the proper files

Download the PDF file .

Chapter 10 Editing UITableView

Editing Mode

UITableView has an editing property, when set to true UITableView enters editing mode. Editing mode does not allow user to edit content of row.

Header View appears in the top of the table. Header is used to describe table headers and section headers.

In Homepwner, add the following to ItemsViewController.swift:

screen-shot-2016-10-21-at-12-28-03-pm

  • In Main.storyboard, drag a View to the top of the tableView and resize the height to be 60 pts.
  • Drag two buttons into the header view.
  • Select both buttons and open Auto Layout align and select Vertically in Container.
  • Update frames.
  • Open pin menu and configure as shown below

screen-shot-2016-10-21-at-12-36-49-pm

  • Connect buttons to ItemsViewContoller, select toggleEditingMode for edit and addNewItem for add

Add the following to toggleEditingMode button:

screen-shot-2016-10-21-at-12-45-05-pm


Adding Rows

Most common interfaces for adding rows at runtime:

  • A button above cells of the table view
  • A cell with a green plus sign

Add the following to addNewItem:

screen-shot-2016-10-21-at-12-51-58-pm

DataSource of the UITableView determines the number of rows the table view will display.

The following is snippet of code allows for a row to be added to the list.

screen-shot-2016-11-11-at-12-04-29-am

Since you are now able to add Items to to the ItemStore, the initializer that adds 5 items to the list should be removed from the ItemStore leaving the ItemStore as shown below.

screen-shot-2016-11-11-at-12-05-23-am


Deleting Rows

Adding functionality to the red circles on each row. When deleting a cell you must do two things remove the row from UITableView and remove the item from the ItemStore.

To do this ItemStore must be able to delete an item, add the following to functions to ItemStore.swift

screen-shot-2016-11-11-at-12-57-20-am

Also add the following to ItemsViewController.swift.

screen-shot-2016-11-11-at-1-10-37-am


Moving Rows

To be able to change the order of the items in the list a method to do so must be added to ItemStore.swift.

screen-shot-2016-11-11-at-1-17-06-am

As well as ItemsViewController.swift

screen-shot-2016-11-11-at-1-20-17-am


Display User Alerts

Add the following to ItemsViewController.swift, this will create a user warning using the .ActionSheet style which allows the user to deny or back away from the alert without making a decision.

There are two types of styles for alerts:

  • UIAlertControllerStyle.ActionSheet – used to present the user with a list of actions from which to choose from. This method is used if a user can back out of a decision or the action is not critical.
  • UIAlertControllerStyle.Action – used to display critical information o require the user to decide how to proceed.

screen-shot-2016-11-11-at-3-14-45-am

Modal View Controller – takes over the screen until it has finished.


Design Pattern – solves common software engineering problems. Contains ideas and/or approaches to use in the application.

Types of Design Patterns:

  • Delegation – one objects gives certain responsibilities to another object.
  • Data Source – is responsible for providing data to another object when requested.
  • Model-View-Controller – each object fulfills a role:
    • model – data
    • view – displays the user interface
    • controller – ties the model and view together
  • Target-action pairs – one objects calls a method on another object

Download the PDF file .

Chapter 9 UITableView and UITableViewController

UITableViewController

Model – holds data and knows nothing about the user interface.

View – is visible to the user and knows nothing about the model objects.

Controller – keeps the user interface and the model objects in sync and controls the flow of the application.

UITableView is a view object and doesn’t handle application logic or data. It typically needs a view controller to handle its appearance on the screen. I needs a data source. UITableView asks the data source for the the number of rows to display and the data to be shown. Without the data source the UITableView is an empty container. Any type of object can be a data source if it conforms to the UITableViewDataSource protocol.

An instance of UITableViewController class can be a view controller, data source, and a delegate.

UITableViewController is a subclass of UIViewController. UITableViewController’s view is always an instance of UITableView and the UITableViewController handles the preparation and presentation of the UITableView.


Subclassing UITableViewController

Implementing a subclass of UITableViewController for Homepwner. Create a new file named ItemsViewController. Define UITableViewController subclass named ItemsViewController.

screen-shot-2016-10-21-at-12-27-32-am

In Main.storyboard, delete the View Controller. Drag a Table View Controller onto the canvas. In the identity inspector change the class to ItemViewController. In the attributes inspector, check the box for Initial View Controller. Then delete the ViewController.swift file.


Creating the Item Class

Create a new Item.swift file.

screen-shot-2016-10-21-at-12-27-32-am

Item inherits from NSObject (base class that most Objective-C classes inherit from). SerialNumber is an optional String because an item doesn’t have to have a value.


Custom initializers

Structs do not support inheritance. Classes can have two kinds of initializers: designated initializers and convenience initializers. Every class has at least one designated initializer.

Designated initializer – ensures all properties in a class have a value.

screen-shot-2016-10-21-at-3-45-13-am

Free initializer – init() is useful when all your class properties have default values and do not need new instances.

Convenience initializers – always call another initializer on the same class.

screen-shot-2016-10-21-at-4-05-22-am


UITableView’s Data Source

Create a new Swift file named ItemStore.

screen-shot-2016-10-21-at-4-12-36-am


Giving the controller access to the store

In ItemViewController.swift add:

screen-shot-2016-10-21-at-4-16-00-am

In AppDelegate.swift add:

screen-shot-2016-10-21-at-4-14-52-am

In ItemStore.swift add:

screen-shot-2016-10-21-at-4-16-41-am

Dependency inversion principle – goal is to decouple objects in inverting dependencies between them. States that high-level objects should not depend on low-level objects, both should depend on abstraction. Also states that abstractions should not depend on details, details should depend on abstractions.

Dependency injection – high-level objects do not assume which low-level objects they need to use, instead they are passed through an initializer or property.


Implementing data source methods

In ItemsViewController.swift add:

screen-shot-2016-10-21-at-4-27-27-am


Creating and retrieving UITableViewCells

In ItemsViewController.swift add: this will display the contents in allItems array

screen-shot-2016-10-21-at-4-32-29-am

Reusing UITableViewCells

iOS devices have a limited amount of memory, reusing cells saves space. Reusing cells essentially tells the table view  to return a cell with the same class.

In Main.storyboard, select the prototype cell and open the attributes inspector. Change style to Right detail and give it an identifier of UITableViewCell.

In ItemsViewController.swift add:

screen-shot-2016-10-21-at-4-32-56-am

Content Insets

In ItemsViewController.swift add:

screen-shot-2016-10-21-at-5-09-55-am

So far, the application has been taking up the entire screen not leaving room for the status bar. This cade snippet adds padding at the top of the screen.

Chapter 7: Localization

Internalization (i18n): making sure that cultural information such as language and currency are not hardcoded into the application.

Localization (L10n): The process of providing the appropriate data in the application based on the user’s Language and Region Format settings.


In this chapter NSNumberFormatter and NSNNumber classes were used to internationalize the ConversionViewController.

Formatters

NSNumberFormatter has a locale property which is set to the device’s current locale. Every time NSNumberFormatter is used to create a number, it checks its locale property and sets the format accordingly.

NSLocate knows how different regions display symbols, dates, decimals, and whether they use the metric system.


Base Internationalization

Localization -usually involves either generating multiple copies of resources (images, sound, files) for different regions, languages, and string tables

Main Bundle: is created when you build a target in Xcode. All the resources added to the target are copied to the bundle along with the executable itself.

Localizing a resource puts another copy of the resource in the application bundle and are organized by language-specific directories (lproj)

Base Internalization: Xcode specific feature that simplifies the process of localizing interface files.


Preparation for Localization

Preview Assistant (Opt+Cmd+Return): previews how the interface will look across different screen sizes, orientations, and between different localized languages.

+ sign at the lower left corner allows you to add additional screen sizes to the preview canvas.

Button on the lower right allows you to select a language to preview the interface.

Pseudolanguage: helps internationalize the application before receiving translations for all the strings and assets.

The built in Double-Length Pseudolanguage mimics languages that are more verbose by repeating whatever text string is in the text element.

  • A problem with the Double-Length Pseudolanguage is that the contraints must be adjusted to fit the repeating words.
  1. Select label and add constraints by using Ctr+drag label to the left side of the superview
  2. Select Leading Space to Container Margin in the pop-up
    • direction of the drag determines possible constraints displayed: vertical drag shows vertical constraints, horizontal drag shows horizontal constraints, diagonal drag shows both vertical and horizontal constraints
  3. Ctr+drag label to the right of the superview and select Trailing Space to Container Margin
  4. Select the leading constraint by clicking on the I-bar to the left of the label
  5. Open its attributes inspector and change Relation to Greater Than or Equal and Constant to 0
  6. Repeat for other labels

Chapter 6: Programmatic Views

Creating a View and Constraints Programmatically

Update WorldTrotter:

  1. Remove view from storyboard so that it can be created programmatically. In Main.storyboard, select map view and delete.
  2. Open MapViewController.swift and override loadView() and create a property for map view. When a view controller is created the property is set to nil.screen-shot-2016-09-30-at-11-57-39-am
  3. Update loadView() to add programmatic constraints to the application.screen-shot-2016-09-30-at-12-16-29-pm

Autoresizing masks: used before auto layout to allow views to scale for different screens at runtime.


Anchors

Anchors: properties of the view that correspond to attributes that you might want to constrain to an anchor on another view.

screen-shot-2016-09-30-at-12-31-55-pm

Common Ancestor: A common view higher up the hierarchy. If a constraint only has a single view then that view is considered the common ancestor.

Layout guides: indicate the extent to which the view controller’s view content will be visible. There are three anchors that can be used to add constraints.

  1. topAnchor
  2. bottomAnchor
  3. heightAnchor

screen-shot-2016-09-30-at-12-47-42-pm

Margins: ensures that the application’s content looks good on different devices by using the margins of the view controller’s view.

screen-shot-2016-09-30-at-12-47-08-pm

Programmatic Controls:

  1. UIControlEvents.TouchDown – a touch down on the control
  2. UIControlEvents.TouchUpInside – a touch down followed by a touch up while still within the bounds of the control
  3. UIControlEvents.ValueChanged – a touch that causes the value of the control to change
  4. UIControlEvents.EditingChanged – a touch that causes an editing change for a UITextField

 

 

Chapter 5: View Controllers

Lazy Loading: when the view controller’s view is not created until it needs to appear on the screen.

Two ways that a view controller can create its view hierarchy:

  1. programmatically, overriding the UIViewController method loadView()
  2. in Interface Builder, by using an interface file such as storyboard

Initial View Controller: acts as an entry point into the storyboard. Each storyboard has exactly one initial view controller.


Add and configure another view controller to the canvas and set it to be the initial view controller for the storyboard.

  1. Open Main.storyboard
  2. From object library, drag a View Controller onto the canvas
    • The view controller should display an MKMapView-class designed to display a map-instead of the white UIView.
  3. Select the view of the View Controller and press delete to remove the view from the canvas.
  4. Drag a Map Kit View  from the object library  onto the view controller to set it as the view for this view controller.
  5. Select View Controller and open its attributes inspector.
  6. Under the View Controller section, check the box next to “Is Initial View Controller.”
    • The gray arrow indicated the initial view controller.

Framework – a share library of code that includes associated resources such as interface files and images.

  • ex: import UIKit
  • if you include a framework using the import keyword without using any code that uses the framework, the compiler will optimize it out.

Manually link MapKit framework for MKMapView to work:

  1. With the project navigator open, click on WorldTrotter project and open project settings.
  2. Find and open general tab in the settings.
  3. Find section labeled “Linked Frameworks and Libraries.”
  4. Click on the “+” symbol and search MapKit.framework.
  5. Select the framework and click add.

UIWindow has a rootViewController property- when a view controller is set as the window’s rootViewController, the view gets added to the window’s view hierarchy. When the property is set an existing subviews on the window are removed and the view controller’s view gets added to the window with the appropriate Auto Layer constraints.

Main Interface: reference to a storyboard. Each application has one main interface and gets set in the project settings.

When the application launches, the initial view controller for the main interface gets set at the rootViewController of the window.


Tab Bar

UITabBarController keeps an array of view controllers and maintains a tab bar.

  1. Open Main.storyboard and select View Controller.
  2. From the Editor menu, choose Embed In -> Tab Bar Controller.
  3. Add the Conversion View Controller to the Tab Bar Controller’s view hierarchy
  4. Control + drag from Tab Bar Controller to the Conversion View Controller.
  5. From Relationship Segue section, choose view controller.
  6. Build + Run

Each tab on the tab bar can display a title and an image.

  • ex/ The favorite, recent, contacts, keyboard, and voicemail tabs on an iPhone.

Adding Images

  1. In project navigator, open Asset Catalog (open Assets.xcassets).
  2. Drag images into the images set list on the left of the Asset Catalog. Can be set programmatically or in a storyboard.
  3. In Main.storyboard, locate the View Controller. Select the tab bar item and open attributes inspector.
  4. Under Bar Item, change “Title” to “Map” and choose MapIcon from Image menu.
  5. Build + Run

https://iosappdevelopment.chelseairizarry.org/vocabulary/chapter-5-vocabulary/

Chapter 4: Text Input and Delegation

WorldTrotter continued…

Steps:

  • Add a UITextField
  • Open Main.storyboard
  • Select and delete first label (labels will turn red due to anchoring, ignore this for now)
  • Drag a text field from the library to the top of the canvas where the previous label was
  • Set up constraints
  • Open Pin Menu give top and bottom constraints 8 pts and a width 250.
  • Open Align menu select Horizontal Centers with a constraint of 0, update all frames, and add 1 constraint
  • Open attribute inspector and set the text color, font, alignment, placeholder value, and border style
  • Build and run application
  • Select Keyboard ->Toggle Software Keyboard (Cmd+K)
  • Select Keyboard Type as Decimal and change correction and spell check to no.
  • Build and run application

 

Chapter 4 vocabulary

Chapter 3: Views and the View Hierarchy

View Objects: is an instance of UTView or one of its subclasses, knows how to draw itself, can handle events, exists within a hierarchy of views whose root is the application’s window.

Subview: when a view is added to a window


  • Create a New Project: File ->New ->Project
  • First open the ViewController.swift file and delete the any methods inside the class.

Framework: a collection of related classes and resources. ex/ UIKit is a framework.

  • In ViewController.swift override viewDidLoad()
  • Create a CGRect

CGRect-Contains the members of origin and size. The origin is a structure of type CGPoint and contains two CGPoint properties, x and y

  • Create a UIView and set the color

screen-shot-2016-09-23-at-6-04-23-am

  • build a run the program
  • add a second subview

screen-shot-2016-09-23-at-6-08-05-am

  • Delete practice code, add some new views and set their frames.
  • open attribute inspector (4th tab in the utilities area) or cmd+opt+4
  • change size to iPhone 4.7-inch, this will resize the interface to match the dimension of the device
  • From the object library drag 5 instances of UILabel and arrange them on the canvas.
  • Select the top layer, open the size inspector (Cmd+Opt+5)
  • Under View section find Frame Rectangle, these values dictate the position of the view on the screen
  • In Main.storyboard select background view and change the background view attributes
  • Build and run the program

Width/Height: determines the alignment rectangle’s size

Top/Bottom/Left/Right: determines the spacing between the given edges between different alignment rectangles.

Center X/Center Y: determine the center point of the alignment rectangle

Baseline: typically the bottom attribute.

Leading/Trailing: these are language specific attributes. If the language reads left to right the leading attribute is the same as the left attribute and the trailing attribute is the same as the right attribute.


Nearest Neighbor: closest sibling view in the specified direction. If there are no sibling views in the specified direction the nearest neighbor is the superview.

Intrinsic Content Size: the size that the view naturally wants to be.

Misplaced View: means the frame for the view in the Interface Builder is different than the frame that Auto Layout computed.

Chapter 3 vocabulary

Chapter 2: The Swift Language

This chapter focuses on developing an understanding of the basis of Swift language.

The three basis Swift groups are structures (structs), classes, and enumerations (enums).

All three groups can have:

  • properties: values associated with a type
  • initializers: code that initializes an instance of a type
  • instance methods: functions specific to a type that can be called on the type itself
  • class or static method: function specific to a type that can be called on the type itself

Standard types:

Numbers: Int, Float, Double

Boolean: Bool

Text: String, Character

Collection: Array<T>, Dictionary <K: Hashable, V>, Set<T: Hashable>


Playground: Allows code to be written and checked without having to consistently run the application. The result of each line of code will appear in the sidebar.

Creating a Playground:

  1. In Xcode: Select File-> New-> Playground
  2. Select a file name, choose iOS platform and hit next

If an error occurs in the code it is indicated by a red symbol on the left of the line. When clicked the symbol will give more information about the error. The error will prevent any further results from appearing in the sidebar.


Var-denotes a variable

Let-denotes a constant. Opt+click gives more information about the constant or any symbol.

  • literal string:  var str=”Hello, world!”
  • setting a constant: let constStr=str

Type Inference: the compilers infers the data type from the initial value. Neither the string nor the constant above had specified types due type inference.

Specifying types

  • var nextYear: Int
  • var bodyTemp: Float
  • car hasPet: Bool

Swift standard library offers three collections:

  1. arrays: ordered collection of elements of a certain type
  2. dictionaries: unordered collection of key value pairs
  3. sets: unordered number of elements of a certain type

Array: var arrayOfInts: Array<Int> or var arrayOfInts: [Int]

Dictionary: var dictionaryofCapitalsByCountry: Dictionary<String, String> or var dictionaryofCapitalsByCountry: [String, String]

Set: var winningLotteryNumbers: Set<Int>


Property: a value associated with the instance of a type.

Instance Method: a function that is specific to a particular type and can be called on an instance of that type.

Optional: Swift types can be optional which is indicated by appending ? to a type name. An optional allows the possibility that the variable may not store any value.

  • forced unwrapping- append ! to its name.
    • let avgReading = (reading1! + reading2!) / 3
  • optional binding- uses an if/let statement.
    • if let r1= reading1
      • r2 = reading2 { let avgReading = (r1+r2) / 3}
    • else { let errorString = “reported reading was nil” }

Loop examples

C style in Swift:

for var i = 0; i < countingUp.count; i++ { let string = countingUp[i] }

 

Using Range:

let range = 0.. < countingUp.count

for i in range { let string = countingUp[i] }

 

Using enumerate():

for (i, string) in countingUp.enumerate() {…}


Enumeration examples

enum PieType{

case Apple

case Cherry

case Pecan

}

let favoritePie=PieType.Apple


Switch example-

let name: String

switch favoritePie {

case .Apple

name = “Apple”

case .Cherry:

name = “Cherry”

case .Pecan

name = “Pecan”

}

Chapter 2 Vocabulary:

Chapter 2 vocabulary

Chapter 1: A Simple iOS Application

Chapter 1 consisted with getting accustomed to using XCode to create applications. The chapter provided step by step instruction on how to create a working application. The first application in the book was the Quiz application in which you learn the basis of how to do certain motions without fully understanding how it works.

Topics covered:

  • Building and running programs
  • Creating labels and buttons
  • Auto fitting view constraints between a scene on a canvas and the device screen
  • How to declare and set an outlet
  • Defining and setting action methods
  • Declaring objects
  • Adding application icons
  • Setting a launch screen
Quiz app sample
Quiz application view

Code:

provided by Big Nerd Ranch
-Provided by Big Nerd Ranch

 

Chapter 1 vocabulary:

Chapter 1 vocabulary