0% found this document useful (0 votes)
31 views164 pages

Unit 1 Swift. Playground Class Presentataion

This document provides an introduction to basic programming concepts like variables, data types, classes, objects, and the model-view-controller architecture. It explains that variables store values and there are different variable types like integers, floats, Booleans, and strings to store different kinds of data. Classes define attributes and behaviors of objects using methods. Objects are instances of classes that have unique attribute values. The model-view-controller pattern separates an app into independent sections for data, display, and logic/interactivity.

Uploaded by

sujathaumcet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views164 pages

Unit 1 Swift. Playground Class Presentataion

This document provides an introduction to basic programming concepts like variables, data types, classes, objects, and the model-view-controller architecture. It explains that variables store values and there are different variable types like integers, floats, Booleans, and strings to store different kinds of data. Classes define attributes and behaviors of objects using methods. Objects are instances of classes that have unique attribute values. The model-view-controller pattern separates an app into independent sections for data, display, and logic/interactivity.

Uploaded by

sujathaumcet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 164

Mobile Programming

Unit 1
Introduction to Programming
 Building Blocks
 Variables
 Integer
 Float
 Boolean
 Class
 Object
Basic Building Blocks
 Variables
 Bank account balance, it shows the current amount of money you have
available. Your bank account may be $100 at the beginning of the month,
and $350 on your payday.
 This is an example of a variable.
 A variable is a representation of a value.
 Variables come in many different shapes and sizes.
 Different types of variables hold different types of values.
 Numbers, letters, words, true, false, or even a custom car.

 Integer
 An integer is a whole number, a number without any decimal places,
positive or negative: Example -10, 0, 100, 21031
 An integer could be used for the number of stars for a movie review, a
house’s street address, or the score for a sports team.
Basic Building Blocks
 Float
 need to be more precise with a value.
 In the case of currency, a decimal place is used to keep track of the cents on a
dollar $10.51
 A decimal-based variable is called a float. Float is short for floating point,
another name for a decimal place

 Boolean
 Respond with either Yes or No.
 cannot respond with 7, $103.45, or “Banana.”
 Yes or No variable is referred to as a Boolean.
 Similar to a light switch—they are either on or off,true or false; there is no in-
between value
Basic Building Blocks
 String
 Name - collection of letters that form a set of words
 Eg:"SteveDerico"
 A string is used to represent characters strung together to make words
and sentences.
 A string can hold a series of letters, numbers, and symbols. Strings are
surrounded by a pair of quotes. For example:
 "Steve is cool."
 "Where is the ball?"
 "Go Giants
Basic Building Blocks
 Classes
 Different types of automobiles –different –few core
characteristics
 wheels, an engine, and brakes
 Core characteristics are called attributes.
 purpose and provides value to the consumer.
 A car can drive, honk, brake, and steer. Basic methods are
available in every car.
 Without these methods, it would not be a car. These core methods
are called behaviors.
 Designing a new car, a blueprint would be a good place to start.
 Blueprint is a document that serves as a template for building
something. Blueprint defines the attributes and behaviors of the car
Basic Building Blocks

Car blueprint

Has Wheels Class is a blueprint for a virtual object.


Has Engine
Has Brakes Class defines the required attributes and
Can Drive Forward behaviors.
Can Stop
Can Steer Left and Right
Just like a cookie cutter, a class can produce
endless objects from a single
blueprint.
 Has –attributes
 Can -Behaviors
Basic Building Blocks

Green station wagon


 Objects Wheels- Standard
Engine- Diesel
 Attributes make them unique Brakes -Standard
 Each of these cars is an object from the car class. Acceleration -Poor
Stopping -Great
 Object is the product produced by a class. Steering -Fair
 An object has the attributes and behaviors from its
class, in this case, the car class.
 Instance and object are commonly used as synonyms
Red sports car
 combination of the values with their associated Wheels Big
Engine Big
attributes is what makes an object unique. Brakes Performance
Acceleration Great
 Humans have hundreds of attributes and thousands Stopping Great
of possible values for each attribute. Steering Great
Basic Building Blocks

 Methods
 computer processes a list of steps to achieve a task. This
list of steps is called a method.
 A method is a collection of code to complete a specific
task
 Example –Cooking Process
Basic Building Blocks

Car
 Inheritance Wheels Standard
Engine Standard
 passing down of attributes and behaviors from
Brakes Standard
parent to child is called inheritance. Can Drive Forward
 Inheritance is the ability for a class to extend or Can Stop
override functionality from a parent class. Can Steer Left and Right
 Example - class you created was the parent of SUV
the SUV class. Wheels Mud
 SUV class will inherit all the attributes and Engine V8
behaviors of the car class. SUV will also be Brakes Standard
Drive System All-Wheel
able to add its own attributes and behaviors.
Can Drive Forward
Can Stop
Can Steer Left and Righ
Can Drive Uphill
Can Tow a Boat
Basic Building Blocks

 Override the inherited attributes.


 Overriding is the ability to change how an attribute or behavior
works for a class.
 This allows the SUV class to customize and control the inherited
attributes and behaviors the SUV class has an engine, but it is a V8
engine.
 The child class is often referred to as a subclass of the parent class.
In this case, the SUV class is a subclass of the car class.
Model View Controller
 Model-View- Controller architecture helps to
organize your code into three distinct parts.
l
Model View Controller
Model
 Portion of code has to do with the data.
 For example, consider creating an application
that stores all your friends’ contact
information.
 Model portion would hold the phone numbers
and addresses.
 Containing zeros and ones
l
Model View Controller
View
 Code contains all the code related to the user
interface.

 view is like a picture frame; it holds and


displays a picture, but it doesn’t know what
picture it is displaying

 View code should not be connected to the


content it is displaying.

 This way, if the interface is changed, it doesn’t


affect the content.
l
Model View Controller
Controller
 All the logic and decision-making code.
 Like a traffic cop; he directs the others where to go.
 It talks to the view and the model directly.
 The controller responds to taps on the screens, pulls
data from the model, and tells the view what to
display.
 The model and view never speak directly to each
other. All communication goes through the
controller.
first app
Xcode
 Open up Xcode.
 If you don’t see Xcode in your Dock,
 click the Spotlight search icon in the
upper-right corner of your screen. Type
in Xcode and click Top Hit
 Click “Create a New Xcode Project.”
 Next, you will see the project template dialog
 Select Single View Application and click Next.
 fill in details for your new project
Project
Navigator
 like Finder on Mac.
 It provides an easy way to
explore and open the files
in project.
 The folders inside the
Project Navigator are called
groups
Editor
 Editor displays whichever file is selected in the Project
Navigator.

 project is selected in the Project Navigator on the left.


Inspector
 The right sidebar is called the Inspector .
 Inspector is where details for whichever
file is shown in the Editor can be
changed.
 Inspector is dynamic and will change
depending on the file you have selected
inside the Editor
Toolbar
 Top portion of the Xcode window is called the Toolbar.
 Play and Stop buttons. These buttons are used for running and
testing your app.
 Middle, you will find the Activity Viewer. This box will provide
updates as your code is being processed.

 In the upper-right corner, you will find two sets of buttons.


Toolbar
 The first button, with horizontal lines on it, will present the
Standard Editor.
 The Standard Editor is the single view editor you typically see
when you first start a new project.
 Interlocking circles on it, is called the Assistant Editor
 Version Editor -Track and analyze changes made to your project
Buttons
 Set of buttons, in the upper right of screen, are used to hide or show
the three major sections of Xcode.
 First button will hide or show the Project Navigator.
 Second button will hide or show the Debugger.
 Third button will hide or show the Inspector.
 These buttons are especially helpful if you are working on a small
screen.
Storyboards

 Represent the user interface, or interface, for short. Storyboards


hold all the buttons, graphics, and design elements for the
application.
 Storyboards can stretch and scale to fit any size screen from
iPhone to iPad.
 Select Storyboards on Project Navigator
Object Library
 Object Library holds the user interface elements
you will use in your design
 Scroll down through the Object Library until
you see Label.
 A Label is a user interface element used to
display text to the user.
 This text is only readable; the user cannot change
this text.
 Click and drag a Label over the Storyboard
 Top of the Inspector is a small toolbar with six icons
 Each of these icons represents a different section of the Inspector.
 Fourth icon from the left. The icon looks like a downward facing arrow,
and it reveals “Show the Attributes Inspector” when you hover over it.
 Attributes Inspector icon. The Attributes Inspector allows you to change
the values for attributes of the selected element on the Storyboard
 Text attribute holds the string displayed by the Label.
 Underneath the Style drop-down menu is a text box with the
 word “Label” inside of it.
 Double-click the text and replace it with “????”. Press Return
 Color attribute will change the
color of the text displayed by the
Label. Click the
 drop-down arrows next to the word
“Color.” Scroll down and click
Other.
 Pick your color and close the Color
Picker.
 font attribute
 Alignment attributes
Label
 Select Button form Object
Library at the bottom of the
Inspector
 Scroll down and drag a Button
onto the Storyboard
 Double-clicking is a shortcut for
changing the text attribute inside
the Inspector &Save
 Designing is complete,hide the Inspector. To hide the Inspector,
look in the upper-right corner of screen.
 Click the square button with a blue stripe on the right side of it. The
blue stripe will turn to black, and the Inspector will be hidden.
 Document Outline
 quick and easy way to select
any element on the
Storyboard
Storyboard
 View file in the Model-View-Controller paradigm.
 The Assistant Editor is currently displaying ViewController.swift.
 ViewController.swift is the controller in Model-View-Controller, and
it holds all the logic for the interface created.
 Two different types of connections between a view and a controller
 action
 Outlet
action
 An action is triggered when a user taps, swipes, or makes a specified
gesture on the interface.
 The action then sends an alert to the controller, where the controller
can decide how to react.
 Actions are commonly used with Buttons.
 For example, a Button is tapped on the interface, and the controller is
alerted.
 The controller can then choose what to do in response to the action.
outlet
 Works in the opposite direction as an action.
 Outlet is a direct link to the view from the controller and is used to retrieve or set
information from an interface element.
 For example, a Label on the interface has a corresponding outlet, allowing the
controller to read and set the Label’s text.
 create these connections between view and controller, draw a line from one side to
the other.
 Select the Label on the Storyboard . Holding the Control key, click and drag from the
Label over to the Assistant Editor
 Drag your cursor immediately under the following words:
 ViewController : UIViewController
 No action on label
 Property using Outlet
 Click the Button in the Storyboard and
Control-drag from it over to the same spot
in the Assistant Editor.
 When you see the horizontal blue line,
release drag
Diving into Swift
What is Swift ?
 Swift is a new programming language created by Apple as the
language of their future.
 Swift was originally announced during the Apple Worldwide
Developer Conference in June of 2014.
 Apple had used Objective-C, originally created for the Mac, for
over 20 years.
 Swift was created to make writing code easier and more concise.
Swift is perfect for beginners and has lowered the barriers so that
anyone can make apps.
Playgrounds
 Playgrounds are a quick and simple way to write your code and test
it immediately.
 Save it in a Separate folder
Creating Variables
 Variables are used for values that will change, or are dynamic.
 Dynamic means that a value could change now or in the future. The var
keyword stands for variable -create, or declare, a variable.
 Variables are referred to by their variable name. The variable name is linked
to the value; if the value changes
 Name should be one word in camel-case. For example:
 varnumberOfYears
 After the variable name comes a colon. This colon tells Xcode you are
about to state the type for the new variable

varnumberOfYears: Int
 Set a value to the variable. The value you set must match the type
of variable; otherwise, the variable will not be created:
 varnumberOfYears: Int = 30
 An equals sign is used to initialize a variable.
 Initialize means to set up or provide the default value to a variable.
Integers
 An integer, a whole number positive or negative, uses the Int keyword.
 var keyword to create a variable with favoriteNumber as the variable
name. Then the colon is used to state the type.
 The variable’s value is set to 4 using the equals sign:
 varfavoriteNumber: Int = 4
Float
 A float, a number with a decimal place, uses the Float keyword.
 var keyword to create a variable and sets accountBalance as the
variable name. colon is used to set the type using the Float
keyword.
 Variable’s value is set to 1203.51 by using the equals sign:
 varaccountBalance: Float = 1203.51
Boolean

 A Boolean, a variable with the value true or false, uses the Bool
keyword.
 var keyword to create a variable and sets isStudent as the variable
name.
 colon is used to state the type using the Bool keyword. Finally, the
variable’s value is set to true by using the equals sign:
 varisStudent: Bool = true
Strings

 A string, a collection of characters, uses the String keyword and is


created with double quotes.
 the var keyword to create a variable and sets firstName as the
variable name.
 colon is used to state the type using the String keyword.
 Finally, the variable’s value is set to "Steve" by using the equals
sign:
 varfirstName: String = "Steve”
 General Syntax : varvariableName: type = newValueHere
Objects
 Variables can also be used to represent objects.
 The keyword for the type is the object’s class name.- class is a blueprint for an object
 It contains all the attributes and behaviors for the objects it creates.
 var keyword to create a variable and sets fastCar as the variable name.
 Then the colon is used to state the type; in this case, the Car keyword is used to create
a car.
 The variable’s value is set to a new car object by using the equals sign.
 This example could work with any custom class:
 varfastCar: Car = Car()
Constants
 not change -use a constant instead of a variable.
 Constants are designed to work with values that will not change
after they are set.
 Once the value has been set, it will remain that value for its entire
lifetime. This consistent value is referred to as static.
 Static means the value will not change now or in the future
 let keyword is used instead of the var keyword. For example:
varnumberOfYears: Int = 30
let name: String = "Steve"
let isMale: Bool = true
varbankAccountBalance: Float = 1034.20
Type Inference
 Swift can automatically detect, or infer, the required type. This is
called type inference, and it simplifies creating a variable.
 Type and colon are no longer required, because Swift can detect
the type of the value provided on the right side of the equals sign.
 Swift then automatically sets the variable’s type to match the type
from the value.

varnumberOfYears = 30
let name = "Steve"
let isMale = true
varbankAccountBalance = 1034.20
Modifying Strings
 String class provides convenient methods like uppercaseString,
where the string is changed to its uppercase value.
 // show the variable after it has been updated
 Execute sequentially
Appending Strings
 string variable and add on to the end of it. This is called appending
 create new, longer strings, add string variables between other strings
Variables in Strings

 Add variables directly into strings using string interpolation.


 String interpolation is a term for creating a string with placeholders
inside of it. Those placeholders are then filled in while the application
is running.
 string is created with double quotes. The placeholder is created with
a \().
 Inside of the placeholder is the variable to be inserted into the string.
 convenient way to convert a non string variable into a string:
Collections

 Hold on to many variables or constants in a container for better


organization.
 Swift provides two collection classes
 Arrays
 Dictionaries
Arrays
 An array is a container that can hold many variables in a specific order.
 An array can hold a nearly unlimited number of items and assigns each item a specific
position value, or index.
 The index is the item’s position inside the array.
 var names: [String] = ["Steve", "Jeff", "Andy", "Andrew”,"Cole", "Mike", "Mikey"]
 Start with the same var keyword, followed by a colon. add a set of brackets with the type
inside the brackets.
 On the other side of the equals sign, start array with an open bracket.
 Inside the bracket, each item is separated by a comma. The array ends with a closed bracket.
 Arrays in Swift must all have the same type., but it cannot hold a mixture of strings and
integers.
 Arrays can only hold variables of the same type.
 Swift can automatically detect the type of variable for a given array
var names = ["Steve", "Jeff", "Andy"]
Navigating arrays
 Each item inside an array has a specific position, or index.
 always start with zero. The first item in the array will be at index 0, the
second item in the array is at index 1
 Names[0],count,Isempty()
Modifying arrays
 Array declared with the var keyword are dynamic and can be changed
Dictionaries
 Dictionaries can hold multiple variables and organize them using
keys and values.
 key is the word user looking for, and the value is the definition of the
word.
 Dictionaries are not sorted or organized in a specific order.
 Use the key to retrieve the value
 Add ,Modify,
 Remove a key/value pair by setting the key to nil. nil is a blank value
Loops
 Repeat a particular section of code.
 For-Condition-Increment
 for-in
 Ranges
For Loop
Three pieces: a variable, a condition, and an increment

for (VARIABLE; CONDITION; INCREMENT) {

for (var counter = 0; counter < 8; counter++) {


liftWeights()
}
for-in

 simple way to iterate through an array or dictionary.


 for-in loop automatically detects the condition and increment.
 It creates a variable for that represents the current item in the array
Ranges
 A range is similar to an array of integers from one number to
another.
 Two types of ranges.
 A closed range is written with three dots and includes the uppermost
number: 1...5
 Half-closed range is written with two dots followed by a less-than
sign and does not include the uppermost number
 1..<5
 //1,2,3,4
Conditional Statements
 If Statement
 used to make decisions
 logic can be defined using a conditional statement like an if statement.
 An if statement determines if a condition is true or false; if the condition
is true,a particular section of code is executed; otherwise, it is skipped

 If else
if isWeekday == true {
getReadyForWork()
if isMale == true { } else if isSaturday == true {
bow() goRunning()
}else{ } else {
curtsy() goToYoga()
} }
Optionals
 Variables that could result in the absence of a value
 Ex :Translation output –no
 valueless state is called nil
 used with any type of variable and are explicitly declared using the ?
symbol next to the type keyword.
 vartranslatedWord: String?
 Process of unwrapping an optional helps to remind the developer to
check and make sure the variable is not nil. There are two steps

vartranslatedWord: String? = translate("cat")


if translatedWord != nil {
//translatedWord has a value vartranslatedWord: String? = translate("cat")
} else{ if translatedWord != nil {
//The translatedWord has no value println(translatedWord!)
}
Diving Deeper
 Apple provides developers with a toolset of classes and methods. This
toolset, also known as a framework, is called Foundation.
 Apple’s frameworks at developer.apple.com.
 Methods, Classess,Objects,SubClassess.Inheritance
 Overridding

Ex:Race Car
Methods
 Methods are a group of steps that work together to accomplish a
specific task.
 Methods are very similar to functions. Methods are a set of steps to
complete a task inside a class or object.
 A function is a set of steps to complete a task that stands alone. These
two items are so similar, they have become synonyms.
 “method” and “function” interchangeably
Methods
funcgoodMorning() {
println("Good Morning")
}

Creating own method starts with the func


keyword.
This keyword is used to declare
the beginning of a new method.

The next item is the method’s name. Method


names also use camel-casing.
 Methods can take input in order to provide a more detailed decision
process
 Input variables like these are called parameters.
 Parameters are outside values that are passed into a method.
 The name and type of the parameter are defined inside the parentheses.
 The parameters passed in will be referred to as the variable name inside
the parentheses
funcgoodMorning(name: String){

println("Good Morning \(name)")

Parameters are defined by first stating the variable name and then a colon followed by
the type of variable.

Multiple parameters can be accepted and are separated by a comma.

funcgoodMorning(name: String, day: String){

println("Good Morning \(name), Happy \(day)")

}
Default value
 Default value to parameter, add an equals sign next to the type and
provide the default value.

funcgoodMorning(name: String = "World", day: String = "Day"){

println("Good Morning \(name), Happy \(day)")

goodMorning()
Return Values
 Methods can do more than accept input and execute steps
 Generate output When a method provides an output value, it is called a
return value.
 Return value is the final product of the method, and it is sent back to
the caller.
 A return value can be any type, but the return type must be declared by
the method
funcsum(a: Int,b: Int) ->Int{
return a + b
}

funccalculateTip(bill: Float, percentage: Float)->Float{


vartip = bill * percentage
return tip
}
Classes
 Blueprint or template to create objects saves time and makes maintenance
much easier.
 Creating virtual objects
 Blueprints in Swift are called a class.
 A class is a blueprint or template for an object. This template can be used
over and over like a printing press to create virtual Objects
Objects & its Behaviour
 Class defines the attributes and behaviors of the object. The attributes
are the characteristics of the object.
 These attributes are defined by properties.
 Properties are variables included in each object.
 Properties of a house would be the exterior color, street number, and
number of bathrooms.
 Behaviors are the methods the object provides. For example, a method
could set the air temperature to 68 degrees, or open the garage, or
enable the alarm system.
Syntax & Properties of
Class
class House {

class House {

varexteriorColor= "Brown"

varcurrentAirTemp= 70

varisAlarmEnabled= false

varisGarageOpen= trueclass you created has four properties, each with


a default value already set
}
Methods
class House {

varexteriorColor= "Brown" funcprepareForDaytime(){


isGarageOpen = true
varcurrentAirTemp= 70 isAlarmEnabled = false
currentAirTemp = 70
varisGarageOpen= false }
varisAlarmEnabled= false }

funcprepareForNighttime() {

isGarageOpen = false

isAlarmEnabled = true

currentAirTemp = 65 }
Creating an Object
 Create an object from a class, call the initializer method.
 The initializer method is a method designed specifically for setting
up new objects.
 If user provided default values for the properties, there is no need to
write an initializer method.
 Xcode will create for you.Theinitializer method is typically
accessed by writing the name of the class followed by two
parentheses
 varmyHouse: House = House() or varmyHouse = House()
Accessing Properties
 Access the value of a property by using dot syntax. Dot syntax is
a format used to access and assign values to properties.
 Dot syntax begins with an object
 varmyHouse = House()
 myHouse.exteriorColor
 myHouse.exteriorColor = "Blue"
Calling Methods
 myHouse.prepareForDaytime()
Subclasses
 Reuse a template instead of starting from scratch
 Start with the parent class and then make changes from there.
 This process of reusing is called subclassing
 Subclassing provides a convenient way to share attributes and
behaviors between a parent and child class
 class Cabin: House {
 }
Inheritance
 Inheritance is the ability to pass down attributes and behaviors
from a parent class to a child class.
 All of the parent class’s properties and methods will
automatically be shared with the child class.
 Sub class can add or change these if needed
Overriding
 Changing the inherited properties or methods in a child class is called
overriding.
 Overriding allows the child class to define its own version of a
particular property or method.
 To override a method, add the override keyword.
 The cabin class defines its own initializer method by using the
init keyword.
 cabin class overrides the initializer method from the House
class, the override keyword is added to the beginning of the
method name.
 initializer method is automatically created for the House class.
 The init keyword is followed by a set of empty parentheses, and
an open brace will begin the initialize method.
 Parent class’s initializer should first be called before the child class
overrides or makes changes.
 Refer to the parent class, use the super keyword. Inside the child
class’s init method, write super.init().
 This will call the parent class’s initializer method.
 Once this is complete, the child class is free to override and make
changes. In this case, the cabin class sets the exteriorColor to
"Red".
Overriding methods
 override a subclass’s methods.

Use the override keyword:


class Cabin: House {
override init(){
super.init()
exteriorColor = "Red"
}
override funcprepareForNighttime(){
startFire()
}
}
Building Multiscreen Apps
View Controllers
 View controllers are the logic portion of the Model-View-
Controller, or MVC, paradigm.
 View Controller is a controller that controls the view.
 The view displays information and receives input from the user,
but it does not make decisions.
 Decisions are made inside the view controller
View Controllers
 Own controller called the UIViewController.
 UIView Controller is part of UIKit.
 UIKit is a set of classes provided to create interface elements.
 UIViewController comes with a view property out of the box.
 View property is connected to a view file, in most cases, a storyboard
file.
 prewritten methods - Methods and properties needed to write
 Makes UIViewController a perfect parent class to use as a template for
user custom class.
class mySubController: UIViewController{
override func viewDidLoad()
{
super.viewDidLoad()
// Do any addition setup after loading the view
}
}
 viewDidLoad() method inside of the mySubController class.
 Override keyword is used to tell Xcode that user would like to add to or change
 UIView Controller’s default viewDidLoad method.
 func keyword declares the method.
 viewDidLoad is the method name user would like to override from UIView
Controller.
 viewDidLoad method does not take any parameters, so the parentheses are left
blank.
 Add a set of open and closed braces. These braces are used to determine the
beginning and end of the method.
 Whenever overriding a method, the first line of code should make a call
to super. super is a keyword used to reference the parent class of the
current class
 Parent class is UIViewController.
 This call to super is important because without it the viewDidLoad()
method call would do absolutely nothing
 call to super.viewDidLoad() sets the foundation.
 Add your own custom code after the foundation is complete:
class mySubController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any addition setup after loading the view
println("The View Has Loaded")
}
}
UINavigationController
 Each of the apps created has only one view.
 Popular apps on iOS use multiple views and transition from left to
right
 UINavigationController
 A UINavigationController can hold many UIViewControllers in an
array.
 Array is a collection type; it holds many items in a specific order.
The navigation controller uses a sorting mechanism called a stack.
A stack sorts items in a first-in, last out order.
 To add a view controller to the navigation controller, push the view
controller on top of the navigation controller
 Topmost view controller in the stack will be displayed to the user.
 To show another view controller on top of the current one, push on the
new view controller.
 To remove the current view from the display, a pop is executed on the
navigation controller.
 A pop removes the topmost item from the stack. In this case, it removes
the current view and displays the previous view
 When a view is displayed inside of a navigation controller, a navigation
bar is added to the top of the current view.
 This navigation bar has three main sections:
 the left UIBar
 ButtonItem, the titleView, and the right UIBarButtonItem
 UIBarButtonItem acts like a typical button, but it lives inside a
UINavigationBar.
 UINavigationBar is the class used to create the navigation bar at
the top of a navigation controller.
 The leftBarButtonItem will automatically become a back button
when another view is shown in the navigation controller.
 The titleView will display the value from the UIView Controller’s
title property
Table View
 Scrolling list of items
 Scrolling list of categories and when the user taps on an item, another
screen with more details
 Combination of a navigation controller and table views.
 Navigation controller controls which view is currently displayed, and the
table view displays the scrolling list of items
 Table views are made up of a few key parts. Each item or row in the list is called a cell.
 A cell is a view used to display an individual row in the table view.
 Table view has many cells, and they are grouped into sections.
 Sections are used to separate rows into Groups.
 Each table view has a header and footer. The header is a view that sits above the cells,
while the footer sits at the bottom after the cells.
 Table view is set to one of two styles. The default style, Plain, lists each row one after
another with no separation
 Grouped, will separate rows by their section and place a divider between each group.
Delegation
 Notification concept is used to alert a controller when an event has
happened inside the app.
 The process of subscribing to or receiving notifications for a particular
event is called delegation.
 Delegation specifies a delegate to receive all notifications.
 Delegate doesn’t just receive the notifications; in most cases, the
delegate must respond to them as well
 When a table view is first being created, there are a series of questions
that must be answered.
 The table view sets a delegate to receive the questions and provide
answers.
 Table view will ask the delegate how many rows should be created. The
delegate could respond with a specific number like 20 or even an integer
variable override the numberOfRowsInSection method:
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) ->Int {
return 10
}
Protocol
 full list of questions are wrapped up inside a protocol. A protocol is a
specific way of doing something
 conforming.
 Conforming is agreeing that you will respond to all of the required
methods in a protocol.
UITableViewController
 UIViewController is a view controller class created by Apple to help set
up the typical methods and properties view controllers needed
 UITableViewController will automatically create a table view and set it to
a property named tableView.
 Specify itself as the delegate and stub out all of the required delegate
methods.
 A stubbed-out method is a term used to describe a method that is declared
with nothing inside of it yet.
 UITableViewController will take care of highlighting and unhighlighting
rows when they are tapped. It makes creating and managing table views
UITableViewDataSource
 Protocol that holds the three required methods for UITableView is
called UITableViewDataSource.
 Protocol gathers information for the number of sections, the number of
rows in each section, and the cells to be displayed.
 first required method is numberOfSectionsInTableView(_:). This
method asks for an integer representing the number of sections in the
table view. Overriding this method is straightforward
override func numberOfSectionsInTableView(tableView:
UITableView) ->Int {
//#warning Potentially incomplete method implementation.
//return the number of sections.
return 0 -Warning

override func numberOfSectionsInTableView(tableView:


UITableView) ->Int {
//return the number of sections.
return 1
}
TableView(_:numberOfRowsInSection:). This method

asks for an integer representing the total number of rows


override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) ->Int {
return 0
}

override func tableView(tableView: UITableView,


numberOfRowsInSection section: Int) ->Int {
return 5
}
 UITableViewDataSource protocol requires that user respond to
table View(:cellForRowAtIndexPath:).
 This method provides the cell for each row in the table view
 The method provides a parameter named indexPath. The indexPath
parameter is an NSIndexPath.
 NSIndexPath has two properties.
 Section property is the index of the current section. The row
property is the index of the current row.
 Counting starts at 0 with all indexes. This means:
 The first row in the first section would have an NSIndexPath of 0,0.
 The fourth row in the first section would have an NSIndexPath of 0,3.
 The first row in the third section would have an NSIndexPath of 2,0
 varcurrentRow = indexPath.row
 varcurrentSection = indexPath.section
five main properties to each UITableViewCell

 textLabel -UILabel displays the main message text.


 detailTextLabel -UILabel displays a subtitle; this label is not
always shown.
 imageView -UIImageView displays UIImage on the left side of
the cell.
 accessoryView -Displays disclosure icons if applicable.
 contentView - UIView, blank canvas that holds all the elements.
four different styles;
 Default - Left-aligned text label, optional imageView, and no detail
TextLabel.
 Value1 -Left-side label with black text; it also has a right-side label
that has smaller blue text and is right-aligned.
 Value2 -Right-side label that is right-aligned and contains blue text;
on the right side is a left aligned label with black text.
 Subtitle -Left-side left-aligned label with black text; it also has a
lower left-side left-aligned ‘label with smaller gray text.

You might also like