Developing Applications for ios

Similar documents
View Controller Lifecycle

ios Mobile Development

ITP 342 Mobile App Dev. Web View

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

Stanford CS193p. Developing Applications for ios. Spring CS193p. Spring 2016

Designing iphone Applications

Lecture 8 Demo Code: Cassini Multithreading

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Assignment III: Graphing Calculator

Why Model-View-Controller?

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

View Controllers CPRE 388

Stanford CS193p. Developing Applications for ios. Spring CS193p. Spring 2016

Assignment IV: Smashtag Mentions

Today s Topics. Scroll views Table views. UITableViewController Table view cells. Displaying data Controlling appearance & behavior

Widget Tour. iphone and ipod touch Development Fall 2009 Lecture 7

Stanford CS193p. Developing Applications for ios. Winter CS193p. Winter 2017

CS193P - Lecture 8. iphone Application Development. Scroll Views & Table Views

Assignment III: Graphing Calculator

Announcements. Today s Topics

Views. A view (i.e. UIView subclass) represents a rectangular area Defines a coordinate space

Assignment III: Graphing Calculator

iphone Application Programming Lecture 5: View Programming

ios Mobile Development

View Concepts. iphone Application Programming Lecture 4: User Interface Design. SDK provide many types of Views to show your content

Assignment III: Graphing Calculator

Developing Applications for ios

User Experience: Windows & Views

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

Announcements. Today s Topics

lecture 10 UI/UX and Programmatic Design cs : spring 2018

CSC 581: Mobile App Development Spring 2018

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Introductory ios Development

Objective-C. Stanford CS193p Fall 2013

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

Objective-C Primer. iphone Programmer s Association. Lorenzo Swank September 10, 2008

iphone Programming Patrick H. Madden SUNY Binghamton Computer Science Department

Introducing the Modern WebKit API

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Using Advanced Interface Objects and Views

iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5

ios Mobile Development

1 Build Your First App. The way to get started is to quit talking and begin doing. Walt Disney

Lesson 1: Hello ios! 1

SAMPLE CHAPTER. Brendan G. Lim Martin Conte Mac Donell MANNING

Structuring an App Copyright 2013 Apple Inc. All Rights Reserved.

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Advanced ios. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 20 11/01/2012

My First iphone App (for Xcode version 6.4)

Building GUIs with UIKit. Kevin Cathey

Event Delivery: The Responder Chain

The MVC Design Pattern

ios Application Development Lecture 5: Protocols, Extensions,TabBar an Scroll Views

Developing Applications for ios

Learn to make desktop LE

Assignment II: Foundation Calculator

Scroll View School Hands-On Challenges

UICollectionView. NSCoder Milwaukee. 2 April John Psuik. Tuesday, April 2, 13

CSC 581: Mobile App Development Spring 2019

ITP 342 Mobile App Dev. Table Views

CUSTOM VIEWS. The View Hierarchy. Chapter 12

Developing Applications for ios

Praktikum Entwicklung von Mediensystemen mit

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

IOS - TEXT FIELD. Use of Text Field. Important Properties of Text Field. Updating Properties in xib

ios Memory Deep Dive #WWDC18 Kyle Howarth, Software Engineer James Snee, Software Engineer Kris Markel, Software Engineer

Custom Drawing & Animation. CS 442: Mobile App Development Michael Saelee

Contents. iphone Training. Industry Trainers. Classroom Training Online Training ON-DEMAND Training. Read what you need

Stanford CS193p. Developing Applications for ios. Spring Stanford CS193p. Spring 2012

Linkify Documentation

Developing Applications for ios

ios DeCal : Lecture 2 Structure of ios Applications: MVC and Auto Layout

User Experience: Windows & Views

Corrections and version notes

A Vertical Slider for iphone

AVAudioRecorder & System Sound Services

Objective-C. Deck.m. Deck.h. Let s look at another class. This one represents a deck of cards. #import <Foundation/Foundation.h> #import "Deck.

View Concepts. iphone Application Programming Lecture 4: User Interface Design. SDK provide many types of Views to show your content

Integrating Game Center into a BuzzTouch 1.5 app

Announcement. Final Project Proposal Presentations and Updates

epicurious Anatomy of an ios app Robert Tolar Haining June 25, 2010 ConvergeSE

Creating Content with iad JS

ITP 342 Mobile App Dev. Table Views

ITP 342 Mobile App Dev. Connections

iphone Application Tutorial

Building Mapping Apps for ios With Swift

Your First iphone OS Application

Building the App - Part 5 - Adding a Link

Mobile Application Development

Create an App that will drop PushPins onto a map based on addresses that the user inputs.

Transitioning Teacher Websites

Mobile Application Development

Developing Applications for ios

Storyboards and Controllers on OS X

QuickPrints SDK for ios Version 3.3 August 06, 2014

Stanford CS193p. Developing Applications for ios. Spring Stanford CS193p. Spring 2012

CS193P: HelloPoly Walkthrough

Transcription:

Developing Applications for ios Lecture 7: View Controller Lifecycle and UIKit Radu Ionescu raducu.ionescu@gmail.com Faculty of Mathematics and Computer Science University of Bucharest

Content View Controller Lifecycle When your controller hears about things and what you should do about it. Image View Kind of like UILabel for images. Web View Complete browser in a view. Scroll View Provides a moving viewport on a rectangular area that has views (the scroll view s subviews) in it.

View Controller Lifecycle View Controllers have a Lifecycle A sequence of messages is sent to them as they progress through it. Why does this matter? You very commonly override these methods to do certain work: - (void)viewdidload; - (void)viewwillappear:(bool)animated; - (void)viewdidappear:(bool)animated; - (void)viewwilldisappear:(bool)animated; - (void)viewdiddisappear:(bool)animated; - (void)viewdidunload; and many other methods.

View Controller Lifecycle We have already talked about the first part of the lifecycle Creation This is done mostly either via a segue or storyboard s: instantiateviewcontrollerwithidentifer: Because of this, we rarely override UIViewController s designated initializer in ios 5. Another option is awakefromnib, but we rarely do that either. If you cannot define your views in a storyboard or a nib file, override the loadview method to manually instantiate a view hierarchy and assign it to the view property. There are better methods to initialize in: viewdidload, viewwillappear:, viewdidappear:.

View Controller Lifecycle After instantiation and outlet-setting, viewdidload is called: - (void)viewdidload; This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadview method. This is an exceptionally good place to put a lot of setup code. But be careful because the geometry of your view (its bounds) is not set yet! If you need to initialize something based on the geometry of the view, use the next method.

View Controller Lifecycle Just before the view appears on screen, you get notified: - (void)viewwillappear:(bool)animated; When this is called, your bounds has been set (via your frame by your superview). Your view will probably only get loaded once, but it might appear and disappear a lot. So don t put something in this method that really wants to be in viewdidload. Otherwise, you might be doing something over and over unnecessarily. Use this to optimize performance by waiting until this method (i.e. just before view appears) to kick off an expensive operation (might have to put up a spinning loading icon though). This method is for geometry-related initialization and lazy execution for performance.

View Controller Lifecycle And you get notified when you will disappear off screen too. This is where you put remember what s going on and cleanup code. - (void)viewwilldisappear:(bool)animated { [super viewwilldisappear:animated]; // Call super in all the viewwill/did... methods. /* Let s be nice to the user and remember * the scroll position they were at */ [self rememberscrollposition]; // We will have to implement this, of course. } /* Do some other clean up now that we have * been removed from the screen. [self savedatatopermanentstore]; /* But be careful not to do anything * time-consuming here, or app will be sluggish. * Do it in the did version or in a thread. */

View Controller Lifecycle There are did versions of both of the previous methods. You can override this method to perform additional tasks associated with presenting the view: - (void)viewdidappear:(bool)animated; You can override this method to perform additional tasks associated with dismissing or hiding the view: - (void)viewdiddisappear:(bool)animated; If you override these methods, you must call super at some point in your implementation.

View Controller Lifecycle Frame changed? Here s a good place to layout subviews manually (if struts and springs are not enough): - (void)view{will,did}layoutsubviews; When a view s bounds change, the view adjusts the position of its subviews. Your View Controller can override these methods to make changes before/after the view lays out its subviews. Called any time a view s frame changed and its subviews were thus re-layed out. For example, autorotation. You can reset the frames of your subviews here.

View Controller Lifecycle Specific notification that rotation will/did happen - (void)willrotatetointerfaceorientation: (UIInterfaceOrientation)anOrientation duration:(nstimeinterval)seconds; - (void)willanimaterotationtointerfaceorientation: (UIInterfaceOrientation)toInterfaceOrientation duration:(nstimeinterval)seconds; - (void)didrotatefrominterfaceorientation: (UIInterfaceOrientation)anOrientation; @property UIInterfaceOrientation interfaceorientation; The interfaceorientation property will have the current (old or new) orientation when each of the above is called. Example use: stop doing anything expensive (e.g. an animation maybe?) in will and resume it in did.

View Controller Lifecycle In low-memory situations, viewdidunload gets called Right after your UIViewController s self.view is set to nil (hopefully freeing up its heap usage). This can only happen if your MVC is not on-screen, of course! This rarely happens, but well-designed code will anticipate it. Even though your outlet pointers are weak and will probably get set to nil automatically, it is good practice to set them to nil here so that we know this for sure. For example, CalculatorViewController s viewdidunload should probably look like this: - (void)viewdidunload { self.display = nil;... } This line was added by CTRL-dragging from Interface Builder to create an outlet. The same for other outlets. If the UIViewController goes back on-screen, viewdidload will be called again.

View Controller Initialization Creating a UIViewController from a.xib file This is the old, ios 4 way. Not covered in this class. You create a.xib file with the same name as your UIViewController subclass. Then use alloc/init to create it. Designated initializer (only if you need to override it; use init otherwise): - (id)initwithnibname:(nsstring *)nibname bundle:(nsbundle *)bundle;

View Controller Initialization Creating a UIViewController s UI in code (no.xib, no storyboard) Override the method - (void)loadview and set self.view. Do NOT implement loadview if you use a storyboard/.xib to create the UIViewController. Do NOT set self.view anywhere else besides in loadview. Do NOT implement loadview without setting self.view (i.e. you must set self.view here). You should NEVER call this method directly. The View Controller calls this method when its view property is requested but is currently nil.

View Controller Initialization Avoid awakefromnib if possible. It is an acceptable place to initialize stuff for a UIViewController from a storyboard/.xib. But try to put stuff in viewdidload, viewwillappear: or the segue preparation code (prepareforsegue:sender:) instead.

UIView's frame Who s responsible for setting a UIView s frame? The object that puts the UIView in a view hierarchy. In Interface Builder, you set all view s frames graphically. You do this by dragging on the little handles (or from Size Inspector). What about the frame passed to initwithframe:? If you re putting it into a view hierarchy right away, pick the appropriate frame. If you are not, then it doesn t really matter what frame you choose (but avoid CGRectZero). The code that eventually does put you in a view hierarchy will have to set the frame.

UIView's frame Setting frames in viewdidload Recall that your final bounds are not set in viewdidload. If you create views in code in viewdidload, pick sensible frames based on the view s bounds then. But be sure to set struts/springs (UIView s autoresizingmask property). You specify the value of this mask by combining the constants described in UIViewAutoresizing using the C bitwise OR operator. Think of adding something in viewdidload as the same as laying it out in Interface Builder. In both cases, you have to anticipate that the top-level view s bounds will be changed.

UIImageView A UIView subclass which displays a UIImage We covered how to create a UIImage in the lecture on Views. How to set the UIImageView s UIImage Use this initializer: - (id)initwithimage:(uiimage *)image; It will set its frame s size to match image s size. Note that the designated initializer is still initwithframe: (inherited from the UIView superclass). You can also set this property (but it will not adjust the frame size): @property(nonatomic, strong) UIImage *image;

UIImageView Remember UIView s contentmode property? It can be set to UIViewContentMode{Redraw,Top,Left,...}. UIViewContentModeScaleToFill is the default. Determines where the image appears in the UIImageView s bounds and whether it is scaled. Highlighted image @property(nonatomic,strong) UIImage *highlightedimage; @property(nonatomic,getter=ishighlighted) BOOL highlighted; Note that you can also rename setters or getters of a @property. The naming convention is not to include verbs in a property (this is why the getter is renamed). To get the highlighted property of myimageview you would use: myimageview.ishighlighted

UIImageView Sequence of images forming an animation For animating more images, set the animationimages NSArray @property. UIImageView class provides controls to set the duration and frequency of the animation: @property(nonatomic) NSTimeInterval animationduration; @property(nonatomic) NSInteger animationrepeatcount; The default value is 0, which specifies to repeat the animation indefinitely. You can also start and stop the animation: - (void)startanimating; - (void)stopanimating; - (BOOL)isAnimating; The startanimating method always starts the animation from the first image in the list.

UIWebView A full internet browser in a UIView Can use it not only to take your users to websites, but to display PDFs, for example. Built on WebKit, an open source HTML rendering framework (started by Apple). Supports JavaScript, but limited to 10 seconds or 10 megabytes of memory allocation: - (NSString *)stringbyevaluatingjavascriptfromstring: (NSString *)script; When scripts are running, the user is not able to interact with the webpage (this is why the limitation is imposed). Example: NSString *title = [webview stringbyevaluatingjavascriptfromstring:@"document.title"];

UIWebView Property to control whether page is scaled to fit the UIView: @property(nonatomic) BOOL scalespagestofit; If YES, then page will be squished or stretched to fit the width of the UIView. If NO, the page will be its natural size and the user cannot zoom inside it. The default value is NO. Property to get the scroll view it uses @property(nonatomic, readonly, strong) UIScrollView *scrollview; Can now set properties in the scroll view to control the scrolling behavior of the web view. If you allow the user to move back and forward through the webpage history, then you can use the goback and goforward methods as actions for buttons.

UIWebView Three ways to load up HTML: - (void)loadrequest:(nsurlrequest *)request; - (void)loadhtmlstring:(nsstring *)string baseurl:(nsurl *)baseurl; - (void)loaddata:(nsdata *)data MIMEType:(NSString *)MIMEtype textencodingname:(nsstring *)encodingname baseurl:(nsurl *)baseurl; We ll talk about NSURLRequest in a moment. Base URL is the environment to load resources out of (i.e., it s the base URL for relative URL s in the data or HTML string). MIME type (Multimedia Internet Mail Extension) says how to interpret the passed-in data. Standard way to denote file types (like PDF). Think e-mail attachments (that s where the name MIME comes from).

NSURLRequest UIWebView + (NSURLRequest *)requestwithurl:(nsurl *)url; + (NSURLRequest *)requestwithurl:(nsurl *)url cachepolicy:(nsurlrequestcachepolicy)policy timeoutinterval:(nstimeinterval)timeoutinterval; NSURL Basically like an NSString, but enforced to be well-formed. Examples: file://... or http://... In fact, it is the recommended way to specify a file name in the ios API. + (NSURL *)URLWithString:(NSString *)urlstring; + (NSURL *)fileurlwithpath:(nsstring *)path isdirectory:(bool)isdirectory; NSURLRequestCachePolicy Ignore local cache; ignore caches on the internet; use expired caches; use cache only (don t go out onto the internet); use cache only if validated.

UIWebView UIWebViewDelegate You can set the delegate property to an object conforming to the UIWebViewDelegate protocol if you want to track the loading of web content. Methods in the UIWebViewDelegate are: - (BOOL)webView:(UIWebView *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype; - (void)webviewdidstartload:(uiwebview *)webview; - (void)webviewdidfinishload:(uiwebview *)webview; - (void)webview:(uiwebview *)webview didfailloadwitherror:(nserror *)error; The navigation type gives you a hint about the user action that generated the request: UIWebViewNavigationType{LinkClicked,FormSubmitted, BackForward,Reload,FormResubmitted,Other}

UIScrollView How do you create one? Just like any other UIView. Drag out in a storyboard or use alloc/initwithframe:. Or select a UIView in your storyboard and choose Embed In > Scroll View from Editor menu. Or add your too big UIView using addsubview: like this: UIImage *image = [UIImage imagenamed:@ bigimage.jpg ]; UIImageView *imageview = [[UIImageView alloc] initwithimage:image]; // now imageview.frame.size is equal to image.size [scrollview addsubview:imageview]; Add more subviews if you want.

UIScrollView All of the frames of the subviews will be in the UIScrollView s content area s coordinate system. (0,0) is the upper left corner of the scroll view. Width and height are given by contentsize.width and contentsize.height. Don t forget to set the contentsize! Common mistake is to do the above 3 lines of code (or embed in Interface Builder) and forget to say: scrollview.contentsize = imageview.bounds.size;

UIScrollView Scrolling programmatically - (void)scrollrecttovisible:(cgrect)arect animated:(bool)animated; Other things you can control in a scroll view Control whether scrolling is enabled through the scrollenabled property. Lock scroll direction to user s first move by setting the directionallockenabled property. The style of the scroll indicators are set via the indicatorstyle property. (call flashscrollindicators when your scroll view appears). Whether the actual content is inset from the scroll view s content area (contentinset property). Note that UIScrollView is the superclass of several UIKit classes including UITableView and UITextView.

UIScrollView Zooming All UIViews have a property (transform) which is an affine transform (translate, scale, rotate). Scroll view simply modifies this transform when you zoom. Zooming is also going to affect the scroll view s contentsize and contentoffset. Will not work without minimum/maximum zoom scale being set scrollview.minimumzoomscale = 0.5; //half its normal size scrollview.maximumzoomscale = 2.0; //twice its normal size Will not work without delegate method to specify view to zoom: -(UIView *)viewforzoominginscrollview:(uiscrollview *)sender; If your scroll view only has one subview, you return it here. More than one subview? It's up to you then.

UIScrollView Zooming programmatically @property (nonatomic) float zoomscale; - (void)setzoomscale:(float)scale animated:(bool)animated; - (void)zoomtorect:(cgrect)zoomrect animated:(bool)animated; Lots and lots of delegate methods! The scroll view will keep you up to date with what s going on. Example: delegate method will notify you when zooming ends - (void)scrollviewdidendzooming:(uiscrollview *)sender withview:(uiview*)zoomview atscale:(cgfloat)scale; If you redraw your view at the new scale, be sure to reset the affine transform back to identity.

Next Time idevice Capabilities: Core Location: GPS + Compass Accelerometer Map Kit