SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Pregame Warmup
u Download and install Xcode (Mac App Store)
u Start Xcode
u If it asks “Install Additional Components”, definitely do so
u Pull up The Swift Programming Language book in a browser
u https://docs.swift.org/swift-book/
Intro to App
Development (iOS)
RANDY SCOVIL, CAL POLY COMPUTER SCIENCE / SOFTWARE ENGINEERING
INIT BY SLOHACKS – 11/10/18
Dive straight in
u Let’s create a simple (and runnable) app
u File -> New -> Project and select Single View App
u Create a product name
u Enter (or make up) and organization
u Make sure language is set to Swift
u When your project appears, click Main.storyboard on the left-
hand side – you should see a View Controller appear in the center
pane (known as Interface Builder)
u Click on the Library button in the upper right to open up a list of
draggable stuff that we will be…dragging.
Make something appear
u Look for and drag a Label onto the View Controller (VC)
u Once done, click on the label and look to the right – click the 4th (down
arrow) icon to get to the Attributes Inspector
u Feel free to tweak the text, color, font, etc. of the label
u In the upper left, click the arrow button to run the app (you can also
use Run from the Product menu or Command-R
u The simulator should appear in the foreground and display your
label in all its majesty
Ok you just built and ran an app
u Thanks for coming, have a great day at init!
Let’s add some more stuff
u Go back to the Library and drag out a Button
u You can change its title by clicking on it or changing the title over on
the right in the Attributes Inspector
u Run the app again, and click the button
Nothing happens…yet
u We need to add some interactivity
u Much of the code we write in apps is written to respond to events,
like a view appearing, someone interacting with the UI (User
Interface), etc.
u Open up the Assistant Editor (interlocking circles in upper right) and
you will see some source code appear in the window that just
appeared.
u We’re going to add some code triggered by the button click
Action Events
u One of the key patterns in iOS is Target-Action – you hit a target,
and an action is generated that we can respond to
u Control-drag from the button into the code window, and release
inside the current braces of the ViewController class
u This pops up the connection window – this is where you create an
action metod in the code that will be triggered by the button click
u Pick a festive name for the method and press Connect
Outlets
u We have the framework for the action method, but we need to give
it something to do…or in this case, something to change
u We’re going to create an outlet that connects the code to an
element in the UI – in this case, our label
u Control-drag again, this time from the label into the
ViewController class (preferably near the top) and release
u Pick a name for the outlet and Connect
Make something happen
u Let’s add some code to the action method that will change the
label’s text to…well, whatever you want
u Start typing the name of the label output inside the method (you
can let the auto-complete finish for you), then add .text, an =, and
then your desired message in quotes, e.g.:
u ourLabel.text = “Something else”
u Run the app again, and press the button!
Some background stuff
u We’ll get back to making thing happen in the UI in a few, but first
some background on what is in our project (check the left side):
u AppDelegate.swift – handles app-level events. Not important yet.
u ViewController.swift - A class that defines a view in the app and
the code to control its interactions (a combination of two elements of
MVC, or Model-View-Controller)
u Main.storyboard – Storyboards allow you to view and edit the
contents of one of more view controllers, as well as transitions between
them (known as segues)
u Assets.xcassets – An asset catalog that holds files like images/icons
u Info.plist – A property list that contains info (settings, etc.) about the
app
The ViewController.swift code
u Importing UIKit – Framework for all UI elements
u ViewController is a subclass of UIViewController from UIKit
u We’re building a custom type and using UIViewController as the starting point
u Classes have properties and methods
u The property we added is our label which is a UILabel
u var means it can be changed (use let for constants)
u viewDidLoad() is a method called when the view first loads
u override replaces the version fromUIViewController ours– using
super.viewDidLoad() incorporates the old version
Adding more stuff
u Head back to the library and find a Slider and drag it in to the
view controller, resizing it as desired
u If you want the library to stay visible, Option-Click the library icon
u You can custom its range of values in the Attributes Inspector
u Control-drag from the slider to the view controller, and generate an
action for the Value Changed event
u Change the Type from Any to UISlider – this tells the method that
what it’s getting is a slider, allowing us to ask for things that sliders have
u Add this code to your method, using the name of your label:
u myLabel.text = String(sender.value)
u Run the app again and move the slider know
Why did we need the String( )
u The String( ) code was necessary since the type returned by
sender.value (Float) is not legally assignable to the text property
of the label (String)
u Therefore we need to make a copy of value that’s in a form that
text can deal with
u String( ) takes that copy of value and creates an equivalent
String to assign to the text property
Entering text and using delegation
u Grab a Text Field from the library and drag it in
u We can use these to allow the user to enter text
u Use the Attributes Inspector if you want to customize the keyboard type
u Text fields can generate a wide range of events, but we might not
care about all of them
u Rather than control-drag action methods, we’re going to
implement a delegate instead to handle its events
Meet our delegate,
ViewController
u ViewController will serve as the text field’s delegate, receiving and
responding to any events of interest generated by the text field.
u We do that by stating that VIewController will conform to the
UITextFieldDelegate protocol
u A protocol is a set of methods, similar to a Java interface, that types implement in
order to provide defined functionality
u First, indicate that ViewController is serving as a text field’s delegate
by adding , UITextFieldDelegate after UIViewController
u You can option-click on UITextFieldDelegate to learn more about
the protocol and its methods
Implement
textFieldShouldReturn()
u Next, define the textFieldShouldReturn() method by starting to
type the header (auto-complete is still your friend)
u Add myLabel.text = textField.text as the first line to take the
text from the text field and assign it to the label
u The Bool after the arrow at the end of the method header is the
return type – we need to return a value of that type every time
u Add return true as the second line, as we want the text field to
conclude its work
A couple issues to address
u When we run it, we find that if we finish typing, the keyboard stays
deployed (if the keyboard doesn’t appear in the simulator, hit
Command-K)
u You can use your Mac keyboard to enter text rather than clicking
u We can fix this by adding textField.resignFirstResponder()
before the return statement – this will retract the keyboard
u Also, the text from the text field isn’t appearing in the label
u While the view controller is all ready to be a UITextFieldDelegate,
the text field doesn’t know who their delegate is (yet)
Designating a delegate
u To fix this we go back to Interface Builder and yes, you guessed it,
control-drag from the text field to the View Controller circle at
the top of the view
u In the pop-up window, select delegate under Outlets
u You can confirm this over on the right in the Connections Inspector,
which will show the connection between the text field and its delegate,
the view controller
u Run the app and soak in the results
Making stuff look nice
u You can use Auto Layout to make things look consistent on devices
of different sizes
u It also can assist you in defining layouts based on relative locations
u You can assign constraints between an item and its surrounding
view (the superview) or between two items
u For simple vertical or horizontal alignment, you can also add
multiple items to a Stack View
Swift
u Swift was introduced by Apple in 2014 to provide a more succinct
modern language for iOS development using ideas from other
programming languages
u In Swift, values are statically typed but what type they are declared
as can be inferred by what they are initialized with
u Custom types include classes, structs, and enums. Structs and
classes are almost identical – in Swift structs are value types, classes
are reference types
u Swift makes extensive use of optional types – any type can be
optional, which means it can hold a value of that type or nil
Thanks
u Keep experimenting and building with iOS!
u Feel free to ask questions on iOS. See you in CSC 436.
u rscovil@calpoly.edu

Contenu connexe

Similaire à Intro to ios - init by SLOHacks

Coding Lesson (iOS for non-developers) by Zakery Kline and Roger Kerse
Coding Lesson (iOS for non-developers) by Zakery Kline and Roger KerseCoding Lesson (iOS for non-developers) by Zakery Kline and Roger Kerse
Coding Lesson (iOS for non-developers) by Zakery Kline and Roger KerseEuropean Innovation Academy
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outletsveeracynixit
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outletsveeracynixit
 
IOS Swift language 1st Tutorial
IOS Swift language 1st TutorialIOS Swift language 1st Tutorial
IOS Swift language 1st TutorialHassan A-j
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
WP7 HUB_Introducción a Silverlight
WP7 HUB_Introducción a SilverlightWP7 HUB_Introducción a Silverlight
WP7 HUB_Introducción a SilverlightMICTT Palma
 
App Inventor : Getting Started Guide
App Inventor : Getting Started GuideApp Inventor : Getting Started Guide
App Inventor : Getting Started GuideVasilis Drimtzias
 
1.2 statements, properties, and operations
1.2   statements, properties, and operations1.2   statements, properties, and operations
1.2 statements, properties, and operationsallenbailey
 
Visual Programming
Visual ProgrammingVisual Programming
Visual ProgrammingBagzzz
 
Session 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architectureSession 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architectureVu Tran Lam
 
"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2Tadas Jurelevičius
 
Code camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una DalyCode camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una DalyUna Daly
 

Similaire à Intro to ios - init by SLOHacks (20)

iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
 
Coding Lesson (iOS for non-developers) by Zakery Kline and Roger Kerse
Coding Lesson (iOS for non-developers) by Zakery Kline and Roger KerseCoding Lesson (iOS for non-developers) by Zakery Kline and Roger Kerse
Coding Lesson (iOS for non-developers) by Zakery Kline and Roger Kerse
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outlets
 
Ios actions and outlets
Ios actions and outletsIos actions and outlets
Ios actions and outlets
 
IOS Swift language 1st Tutorial
IOS Swift language 1st TutorialIOS Swift language 1st Tutorial
IOS Swift language 1st Tutorial
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
unit 4.docx
unit 4.docxunit 4.docx
unit 4.docx
 
WP7 HUB_Introducción a Silverlight
WP7 HUB_Introducción a SilverlightWP7 HUB_Introducción a Silverlight
WP7 HUB_Introducción a Silverlight
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
 
App Inventor : Getting Started Guide
App Inventor : Getting Started GuideApp Inventor : Getting Started Guide
App Inventor : Getting Started Guide
 
1.2 statements, properties, and operations
1.2   statements, properties, and operations1.2   statements, properties, and operations
1.2 statements, properties, and operations
 
Vb.net and .Net Framework
Vb.net and .Net FrameworkVb.net and .Net Framework
Vb.net and .Net Framework
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
Introduction of Xcode
Introduction of XcodeIntroduction of Xcode
Introduction of Xcode
 
Session 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architectureSession 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architecture
 
"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2
 
Code camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una DalyCode camp 2011 Getting Started with IOS, Una Daly
Code camp 2011 Getting Started with IOS, Una Daly
 
ArduinoWorkshop2.pdf
ArduinoWorkshop2.pdfArduinoWorkshop2.pdf
ArduinoWorkshop2.pdf
 
Shiny in R
Shiny in RShiny in R
Shiny in R
 
Swift
SwiftSwift
Swift
 

Dernier

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 

Dernier (20)

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 

Intro to ios - init by SLOHacks

  • 1. Pregame Warmup u Download and install Xcode (Mac App Store) u Start Xcode u If it asks “Install Additional Components”, definitely do so u Pull up The Swift Programming Language book in a browser u https://docs.swift.org/swift-book/
  • 2. Intro to App Development (iOS) RANDY SCOVIL, CAL POLY COMPUTER SCIENCE / SOFTWARE ENGINEERING INIT BY SLOHACKS – 11/10/18
  • 3. Dive straight in u Let’s create a simple (and runnable) app u File -> New -> Project and select Single View App u Create a product name u Enter (or make up) and organization u Make sure language is set to Swift u When your project appears, click Main.storyboard on the left- hand side – you should see a View Controller appear in the center pane (known as Interface Builder) u Click on the Library button in the upper right to open up a list of draggable stuff that we will be…dragging.
  • 4. Make something appear u Look for and drag a Label onto the View Controller (VC) u Once done, click on the label and look to the right – click the 4th (down arrow) icon to get to the Attributes Inspector u Feel free to tweak the text, color, font, etc. of the label u In the upper left, click the arrow button to run the app (you can also use Run from the Product menu or Command-R u The simulator should appear in the foreground and display your label in all its majesty
  • 5. Ok you just built and ran an app u Thanks for coming, have a great day at init!
  • 6. Let’s add some more stuff u Go back to the Library and drag out a Button u You can change its title by clicking on it or changing the title over on the right in the Attributes Inspector u Run the app again, and click the button
  • 7. Nothing happens…yet u We need to add some interactivity u Much of the code we write in apps is written to respond to events, like a view appearing, someone interacting with the UI (User Interface), etc. u Open up the Assistant Editor (interlocking circles in upper right) and you will see some source code appear in the window that just appeared. u We’re going to add some code triggered by the button click
  • 8. Action Events u One of the key patterns in iOS is Target-Action – you hit a target, and an action is generated that we can respond to u Control-drag from the button into the code window, and release inside the current braces of the ViewController class u This pops up the connection window – this is where you create an action metod in the code that will be triggered by the button click u Pick a festive name for the method and press Connect
  • 9. Outlets u We have the framework for the action method, but we need to give it something to do…or in this case, something to change u We’re going to create an outlet that connects the code to an element in the UI – in this case, our label u Control-drag again, this time from the label into the ViewController class (preferably near the top) and release u Pick a name for the outlet and Connect
  • 10. Make something happen u Let’s add some code to the action method that will change the label’s text to…well, whatever you want u Start typing the name of the label output inside the method (you can let the auto-complete finish for you), then add .text, an =, and then your desired message in quotes, e.g.: u ourLabel.text = “Something else” u Run the app again, and press the button!
  • 11. Some background stuff u We’ll get back to making thing happen in the UI in a few, but first some background on what is in our project (check the left side): u AppDelegate.swift – handles app-level events. Not important yet. u ViewController.swift - A class that defines a view in the app and the code to control its interactions (a combination of two elements of MVC, or Model-View-Controller) u Main.storyboard – Storyboards allow you to view and edit the contents of one of more view controllers, as well as transitions between them (known as segues) u Assets.xcassets – An asset catalog that holds files like images/icons u Info.plist – A property list that contains info (settings, etc.) about the app
  • 12. The ViewController.swift code u Importing UIKit – Framework for all UI elements u ViewController is a subclass of UIViewController from UIKit u We’re building a custom type and using UIViewController as the starting point u Classes have properties and methods u The property we added is our label which is a UILabel u var means it can be changed (use let for constants) u viewDidLoad() is a method called when the view first loads u override replaces the version fromUIViewController ours– using super.viewDidLoad() incorporates the old version
  • 13. Adding more stuff u Head back to the library and find a Slider and drag it in to the view controller, resizing it as desired u If you want the library to stay visible, Option-Click the library icon u You can custom its range of values in the Attributes Inspector u Control-drag from the slider to the view controller, and generate an action for the Value Changed event u Change the Type from Any to UISlider – this tells the method that what it’s getting is a slider, allowing us to ask for things that sliders have u Add this code to your method, using the name of your label: u myLabel.text = String(sender.value) u Run the app again and move the slider know
  • 14. Why did we need the String( ) u The String( ) code was necessary since the type returned by sender.value (Float) is not legally assignable to the text property of the label (String) u Therefore we need to make a copy of value that’s in a form that text can deal with u String( ) takes that copy of value and creates an equivalent String to assign to the text property
  • 15. Entering text and using delegation u Grab a Text Field from the library and drag it in u We can use these to allow the user to enter text u Use the Attributes Inspector if you want to customize the keyboard type u Text fields can generate a wide range of events, but we might not care about all of them u Rather than control-drag action methods, we’re going to implement a delegate instead to handle its events
  • 16. Meet our delegate, ViewController u ViewController will serve as the text field’s delegate, receiving and responding to any events of interest generated by the text field. u We do that by stating that VIewController will conform to the UITextFieldDelegate protocol u A protocol is a set of methods, similar to a Java interface, that types implement in order to provide defined functionality u First, indicate that ViewController is serving as a text field’s delegate by adding , UITextFieldDelegate after UIViewController u You can option-click on UITextFieldDelegate to learn more about the protocol and its methods
  • 17. Implement textFieldShouldReturn() u Next, define the textFieldShouldReturn() method by starting to type the header (auto-complete is still your friend) u Add myLabel.text = textField.text as the first line to take the text from the text field and assign it to the label u The Bool after the arrow at the end of the method header is the return type – we need to return a value of that type every time u Add return true as the second line, as we want the text field to conclude its work
  • 18. A couple issues to address u When we run it, we find that if we finish typing, the keyboard stays deployed (if the keyboard doesn’t appear in the simulator, hit Command-K) u You can use your Mac keyboard to enter text rather than clicking u We can fix this by adding textField.resignFirstResponder() before the return statement – this will retract the keyboard u Also, the text from the text field isn’t appearing in the label u While the view controller is all ready to be a UITextFieldDelegate, the text field doesn’t know who their delegate is (yet)
  • 19. Designating a delegate u To fix this we go back to Interface Builder and yes, you guessed it, control-drag from the text field to the View Controller circle at the top of the view u In the pop-up window, select delegate under Outlets u You can confirm this over on the right in the Connections Inspector, which will show the connection between the text field and its delegate, the view controller u Run the app and soak in the results
  • 20. Making stuff look nice u You can use Auto Layout to make things look consistent on devices of different sizes u It also can assist you in defining layouts based on relative locations u You can assign constraints between an item and its surrounding view (the superview) or between two items u For simple vertical or horizontal alignment, you can also add multiple items to a Stack View
  • 21. Swift u Swift was introduced by Apple in 2014 to provide a more succinct modern language for iOS development using ideas from other programming languages u In Swift, values are statically typed but what type they are declared as can be inferred by what they are initialized with u Custom types include classes, structs, and enums. Structs and classes are almost identical – in Swift structs are value types, classes are reference types u Swift makes extensive use of optional types – any type can be optional, which means it can hold a value of that type or nil
  • 22. Thanks u Keep experimenting and building with iOS! u Feel free to ask questions on iOS. See you in CSC 436. u rscovil@calpoly.edu