SlideShare uma empresa Scribd logo
1 de 80
Baixar para ler offline
CS193P - Lecture 5
           iPhone Application Development

           Views
           Drawing
           Animation




Tuesday, January 19, 2010                   1
Announcements

        • Assignment 1 grades are out. Contact Paul or Dave if you didn’t
          get yours

        • Contact Paul or Dave if you need a loaner iPod Touch

        • Assignments 2A and 2B due Wednesday, 1/20




Tuesday, January 19, 2010                                                   2
Questions from Monday?
        • Model, View, Controller

        • Interface Builder & Nibs

        • Delegate
            ■   Allows one object to act on behalf of another object


        • Target-Action




Tuesday, January 19, 2010                                              3
Today’s Topics
        • Views
        • Drawing
        • Text & Images
        • Animation




Tuesday, January 19, 2010   4
Views




Tuesday, January 19, 2010   5
View Fundamentals
        • Rectangular area on screen

        • Draws content

        • Handles events

        • Subclass of UIResponder (event handling class)

        • Views arranged hierarchically
            ■ every view has one superview
            ■ every view has zero or more subviews




Tuesday, January 19, 2010                                  6
View Hierarchy - UIWindow
        • Views live inside of a window

        • UIWindow is actually just a view
            ■   adds some additional functionality specific to top level view


        • One UIWindow for an iPhone app
            ■ Contains the entire view hierarchy
            ■ Set up by default in Xcode template project




Tuesday, January 19, 2010                                                       7
View Hierarchy - Manipulation
        • Add/remove views in IB or using UIView methods
          	 - (void)addSubview:(UIView *)view;
          	 - (void)removeFromSuperview;


        • Manipulate the view hierarchy manually:
          	-    (void)insertSubview:(UIView *)view atIndex:(int)index;
          	-    (void)insertSubview:(UIView *)view belowSubview:(UIView *)view;
          	-    (void)insertSubview:(UIView *)view aboveSubview:(UIView *)view;
          	-    (void)exchangeSubviewAtIndex:(int)index
                      withSubviewAtIndex:(int)otherIndex;




Tuesday, January 19, 2010                                                     8
View Hierarchy - Ownership
        • Superviews retain their subviews

        • Not uncommon for views to only be retained by superview
            ■ Be careful when removing!
            ■ Retain subview before removing if you want to reuse it




        • Views can be temporarily hidden
                theView.hidden = YES;




Tuesday, January 19, 2010                                              9
View-related Structures
        • CGPoint
            ■   location in space: { x , y }


        • CGSize
            ■   dimensions: { width , height }


        • CGRect
            ■   location and dimension: { origin , size }




Tuesday, January 19, 2010                                   10
Rects, Points and Sizes

                     CGRect                                    (0, 0)              x

                                                                              54
             origin                            CGPoint

                                           x         80                 80
              size
                                       y             54
                                                                y



                                                                        144
                                  CGSize

                              width    144
                                                          72
                              height   72



Tuesday, January 19, 2010                                                              11
View-related Structure

      Creation Function           Example

                                  CGPoint point = CGPointMake (100.0, 200.0);
      CGPointMake (x, y)          point.x = 300.0;
                                  point.y = 30.0;

                                 CGSize size = CGSizeMake (42.0, 11.0);
      CGSizeMake (width, height) size.width = 100.0;
                                 size.height = 72.0;

                                 CGRect rect = CGRectMake (100.0, 200.0,
      CGRectMake (x, y,                                    42.0, 11.0);
                  width, height) rect.origin.x = 0.0;
                                 rect.size.width = 50.0;




Tuesday, January 19, 2010                                                       12
UIView Coordinate System
        ■ Origin in upper left corner
        ■ y axis grows downwards



                                        0, 0
                                               +x




                                         +y




Tuesday, January 19, 2010                           13
UIView Coordinate System
        ■ Origin in upper left corner
        ■ y axis grows downwards



                                        0, 0
                                                        +x



                                               UIView


                                         +y




Tuesday, January 19, 2010                                    13
Location and Size
        • View’s location and size expressed in two ways
            ■ Frame is in superview’s coordinate system
            ■ Bounds is in local coordinate system




Tuesday, January 19, 2010                                  14
Location and Size
        • View’s location and size expressed in two ways
            ■ Frame is in superview’s coordinate system
            ■ Bounds is in local coordinate system




                                                View A




Tuesday, January 19, 2010                                  14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                       550
                                                  View A




       400




Tuesday, January 19, 2010                                   14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                       550
                                                            View A frame:
                                                  View A       origin: 0, 0
                                                               size: 550 x 400

                                                            View A bounds:
                                                               origin: 0, 0
                                                               size: 550 x 400

       400




Tuesday, January 19, 2010                                                        14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                       550
                                                            View A frame:
                                                  View A       origin: 0, 0
                                                               size: 550 x 400

                                                            View A bounds:
                                        View B                 origin: 0, 0
                                                               size: 550 x 400

       400




Tuesday, January 19, 2010                                                        14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                       550
                                                            View A frame:
                                                  View A       origin: 0, 0
                                                               size: 550 x 400
                  200, 100
                                                            View A bounds:
                                        View B                 origin: 0, 0
                                                               size: 550 x 400

       400




Tuesday, January 19, 2010                                                        14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                        550
                                                            View A frame:
                                                  View A       origin: 0, 0
                                                               size: 550 x 400
                  200, 100          200
                                                            View A bounds:
                                         View B                origin: 0, 0
                                                               size: 550 x 400

       400                   250




Tuesday, January 19, 2010                                                        14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                        550
                                                            View A frame:
                                                  View A       origin: 0, 0
                                                               size: 550 x 400
                  200, 100          200
                                                            View A bounds:
                                         View B                origin: 0, 0
                                                               size: 550 x 400

       400                   250
                                                            View B frame:
                                                               origin: 200, 100
                                                               size: 200 x 250




Tuesday, January 19, 2010                                                         14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                               550
                                                                  View A frame:
                                                         View A      origin: 0, 0
                                                                     size: 550 x 400
                  200, 100                 200
                                   0, 0                           View A bounds:
                                                View B               origin: 0, 0
                                                                     size: 550 x 400

       400                   250
                                                                  View B frame:
                                                                     origin: 200, 100
                                                                     size: 200 x 250




Tuesday, January 19, 2010                                                               14
Location and Size
        • View’s location and size expressed in two ways
              ■ Frame is in superview’s coordinate system
              ■ Bounds is in local coordinate system

       0, 0                               550
                                                                  View A frame:
                                                         View A      origin: 0, 0
                                                                     size: 550 x 400
                  200, 100                 200
                                   0, 0                           View A bounds:
                                                View B               origin: 0, 0
                                                                     size: 550 x 400

       400                   250
                                                                  View B frame:
                                                                     origin: 200, 100
                                                                     size: 200 x 250

                                                                  View B bounds:
                                                                     origin: 0, 0
                                                                     size: 200 x 250

Tuesday, January 19, 2010                                                               14
Frame is Computed


                            200, 100              View A

                                       200
                                         View B


                                250




Tuesday, January 19, 2010                                  15
Bounds


                                                    View A

                                         200
                                  0, 0     View B


                            250




Tuesday, January 19, 2010                                    16
Center


                                                    View A

                                         200
                                  0, 0     View B


                            250




Tuesday, January 19, 2010                                    17
Center


                                                               View A

                                                    200
                            300, 225         0, 0     View B


                                       250




Tuesday, January 19, 2010                                               17
Frame


                               200, 100                 View A

                                             200
                            300, 225           View B


                                       250




Tuesday, January 19, 2010                                        18
Transform
        • 45° Rotation


                                                            View A




                                              0,
                                              0
                            300, 225




                                                   20 Vi
                                       25




                                                     0 ew
                                          0




                                                       B




Tuesday, January 19, 2010                                            19
Frame
        • The smallest rectangle in the superview’s coordinate system
          that fully encompasses the view itself

                              140, 65          320            View A




                                                0,
                                                 0
                            300, 225




                                                     20 Vi
                                        25




                                                       0 ew
                                           0
                              320




                                                         B




Tuesday, January 19, 2010                                               20
Frame and Bounds
        • Which to use?
            ■   Usually depends on the context
        • If you are using a view, typically you use frame
        • If you are implementing a view, typically you use bounds
        • Matter of perspective
            ■ From outside it’s usually the frame
            ■ From inside it’s usually the bounds




        • Examples:
            ■ Creating a view, positioning a view in superview - use frame
            ■ Handling events, drawing a view - use bounds




Tuesday, January 19, 2010                                                    21
Creating Views




Tuesday, January 19, 2010   22
Where do views come from?
        • Commonly Interface Builder
        • Drag out any of the existing view objects (buttons, labels, etc)
        • Or drag generic UIView and set custom class




Tuesday, January 19, 2010                                                    23
Manual Creation
        • Views are initialized using -initWithFrame:
          	 	 CGRect frame = CGRectMake(0, 0, 200, 150);
          	 	 UIView *myView = [[UIView alloc] initWithFrame:frame];

        • Example:
          	 	 CGRect frame = CGRectMake(20, 45, 140, 21);
          	 	 UILabel *label = [[UILabel alloc] initWithFrame:frame];

          	 	 [window addSubview:label];
          	 	 [label setText:@”Number of sides:”];
          	 	 [label release]; // label now retained by window




Tuesday, January 19, 2010                                               24
Defining Custom Views
        • Subclass UIView

        • For custom drawing, you override:
          	 	 	 	 - (void)drawRect:(CGRect)rect;


        • For event handling, you override:
          -   (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
          -   (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
          -   (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
          -   (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;




Tuesday, January 19, 2010                                                       25
Drawing Views




Tuesday, January 19, 2010   26
- (void)drawRect:(CGRect)rect
        • -[UIView drawRect:] does nothing by default
            ■   If not overridden, then backgroundColor is used to fill


        • Override - drawRect: to draw a custom view
            ■   rect argument is area to draw


        • When is it OK to call drawRect:?




Tuesday, January 19, 2010                                                 27
Be Lazy
        • drawRect: is invoked automatically
            ■   Don’t call it directly!


        • Being lazy is good for performance

        • When a view needs to be redrawn, use:
          	 	 - (void)setNeedsDisplay;


        • For example, in your controller:
          	 	 - (void)setNumberOfSides:(int)sides {
          	 	 	 	 	 	 numberOfSides = sides;
          	 	 	 	 	 	 [polygonView setNeedsDisplay];
          		}


Tuesday, January 19, 2010                              28
CoreGraphics and Quartz 2D
        • UIKit offers very basic drawing functionality
                  UIRectFill(CGRect rect);
          	 	 	 	 UIRectFrame(CGRect rect);
        • CoreGraphics: Drawing APIs
        • CG is a C-based API, not Objective-C
        • CG and Quartz 2D drawing engine define simple but powerful
          graphics primitives
            ■ Graphics context
            ■ Transformations

            ■ Paths

            ■ Colors

            ■ Fonts

            ■ Painting operations



Tuesday, January 19, 2010                                              29
Graphics Contexts
        • All drawing is done into an opaque graphics context

        • Draws to screen, bitmap buffer, printer, PDF, etc.

        • Graphics context setup automatically before invoking drawRect:
            ■ Defines current path, line width, transform, etc.
            ■ Access the graphics context within drawRect: by calling

                	 	 (CGContextRef)UIGraphicsGetCurrentContext(void);
            ■   Use CG calls to change settings


        • Context only valid for current call to drawRect:
            ■   Do not cache a CGContext!


Tuesday, January 19, 2010                                                  30
CG Wrappers
        • Some CG functionality wrapped by UIKit
        • UIColor
            ■ Convenience for common colors
            ■ Easily set the fill and/or stroke colors when drawing


                      UIColor *redColor = [UIColor redColor];
                	 	 	 [redColor set];
                	 	 	 // drawing will be done in red
        • UIFont
            ■ Access system font
            ■ Get font by name


                	 	 	 UIFont *font = [UIFont systemFontOfSize:14.0];
                	 	 	 [myLabel setFont:font];



Tuesday, January 19, 2010                                              31
Simple drawRect: example
        • Draw a solid color and shape
       - (void)drawRect:(CGRect)rect {
          CGRect bounds = [self bounds];

             [[UIColor grayColor] set];
             UIRectFill (bounds);

             CGRect square = CGRectMake (10, 10, 50, 100);
             [[UIColor redColor] set];
             UIRectFill (square);

             [[UIColor blackColor] set];
             UIRectFrame (square);
       }




Tuesday, January 19, 2010                                    32
Simple drawRect: example
        • Draw a solid color and shape
       - (void)drawRect:(CGRect)rect {
          CGRect bounds = [self bounds];

             [[UIColor grayColor] set];
             UIRectFill (bounds);

             CGRect square = CGRectMake (10, 10, 50, 100);
             [[UIColor redColor] set];
             UIRectFill (square);

             [[UIColor blackColor] set];
             UIRectFrame (square);
       }




Tuesday, January 19, 2010                                    32
Drawing More Complex Shapes
        • Common steps for drawRect: are
            ■ Get current graphics context
            ■ Define a path

            ■ Set a color

            ■ Stroke or fill path

            ■ Repeat, if necessary




Tuesday, January 19, 2010                    33
Paths
        • CoreGraphics paths define shapes
        • Made up of lines, arcs, curves and rectangles
        • Creation and drawing of paths are two distinct operations
            ■   Define path first, then draw it




Tuesday, January 19, 2010                                             34
CGPath
        • Two parallel sets of functions for using paths
            ■ CGContext “convenience” throwaway functions
            ■ CGPath functions for creating reusable paths




                        CGContext                   CGPath
          CGContextMoveToPoint           CGPathMoveToPoint
          CGContextAddLineToPoint        CGPathAddLineToPoint
          CGContextAddArcToPoint         CGPathAddArcToPoint
          CGContextClosePath             CGPathCloseSubPath
            And so on and so on . . .




Tuesday, January 19, 2010                                       35
Simple Path Example
       - (void)drawRect:(CGRect)rect {
          CGContextRef context = UIGraphicsGetCurrentContext();

             [[UIColor grayColor] set];
             UIRectFill ([self bounds]);

             CGContextBeginPath (context);
             CGContextMoveToPoint (context, 75, 10);
             CGContextAddLineToPoint (context, 10, 150);
             CGContextAddLineToPoint (context, 160, 150);
             CGContextClosePath (context);

             [[UIColor redColor] setFill];
             [[UIColor blackColor] setStroke];
             CGContextDrawPath (context, kCGPathFillStroke);
       }




Tuesday, January 19, 2010                                         36
Simple Path Example
       - (void)drawRect:(CGRect)rect {
          CGContextRef context = UIGraphicsGetCurrentContext();

             [[UIColor grayColor] set];
             UIRectFill ([self bounds]);

             CGContextBeginPath (context);
             CGContextMoveToPoint (context, 75, 10);
             CGContextAddLineToPoint (context, 10, 150);
             CGContextAddLineToPoint (context, 160, 150);
             CGContextClosePath (context);

             [[UIColor redColor] setFill];
             [[UIColor blackColor] setStroke];
             CGContextDrawPath (context, kCGPathFillStroke);
       }




Tuesday, January 19, 2010                                         36
More Drawing Information
        • UIView Class Reference
        • CGContext Reference
        • “Quartz 2D Programming Guide”
        • Lots of samples in the iPhone Dev Center




Tuesday, January 19, 2010                            37
Images & Text




Tuesday, January 19, 2010   38
UIImage
        • UIKit class representing an image

        • Creating UIImages:
            ■   Fetching image in application bundle
                 ■ Use +[UIImage imageNamed:(NSString *)name]
                 ■ Include file extension in file name, e.g. @”myImage.jpg”

            ■   Read from file on disk
                 ■   Use -[UIImage initWithContentsOfFile:(NSString *)path]
            ■   From data in memory
                 ■   Use -[UIImage initWithData:(NSData *)data]




Tuesday, January 19, 2010                                                     39
Creating Images from a Context
        • Need to dynamically generate a bitmap image

        • Same as drawing a view

        • General steps
            ■ Create a special CGGraphicsContext with a size
            ■ Draw

            ■ Capture the context as a bitmap

            ■ Clean up




Tuesday, January 19, 2010                                      40
Bitmap Image Example
           - (UIImage *)polygonImageOfSize:(CGSize)size {
           	
           	     UIImage *result = nil;

           	
           	         UIGraphicsBeginImageContext (size);
           	
           	
           	
           	         // call your drawing code...

           	
           	         result = UIGraphicsGetImageFromCurrentContext();

           	
           	         UIGraphicsEndImageContext();

           	
           	         return result;
           }




Tuesday, January 19, 2010                                               41
Getting Image Data
        • Given UIImage, want PNG or JPG representation
          	 	 	 NSData *UIImagePNGRepresentation (UIImage * image);
          	 	 	 NSData *UIImageJPGRepresentation (UIImage * image);


        • UIImage also has a CGImage property which will give you a
          CGImageRef to use with CG calls




Tuesday, January 19, 2010                                             42
Drawing Text & Images
      • You can draw UIImages in -drawRect:

         - [UIImage drawAtPoint:(CGPoint)point]
         - [UIImage drawInRect:(CGRect)rect]
         - [UIImage drawAsPatternInRect:(CGRect)rect]



      • You can draw NSString in -drawRect:

         - [NSString drawAtPoint:(CGPoint)point withFont:(UIFont *)font]




Tuesday, January 19, 2010                                                  43
Drawing Text & Images
      • You can draw UIImages in -drawRect:

         - [UIImage drawAtPoint:(CGPoint)point]
         - [UIImage drawInRect:(CGRect)rect]
         - [UIImage drawAsPatternInRect:(CGRect)rect]



      • You can draw NSString in -drawRect:

         - [NSString drawAtPoint:(CGPoint)point withFont:(UIFont *)font]




                            But there is a better way!

Tuesday, January 19, 2010                                                  43
Text, Images, and UIKit views




Tuesday, January 19, 2010               44
Constructing Views
        • How do I implement this?




Tuesday, January 19, 2010            45
Constructing Views
        • How do I implement this?

        • Goal
            ■   PolygonView that displays shape
                as well as name




Tuesday, January 19, 2010                         45
Constructing Views
        • How do I implement this?

        • Goal
            ■   PolygonView that displays shape
                as well as name


        • Initial thought
            ■ Have PolygonView draw the text
            ■ Inefficient when animating




Tuesday, January 19, 2010                         45
Constructing Views
        • How do I implement this?

        • Goal
            ■   PolygonView that displays shape
                as well as name


        • Initial thought
            ■ Have PolygonView draw the text
            ■ Inefficient when animating




        • Instead use UILabel!
            ■ Tastes great
            ■ Less filling



Tuesday, January 19, 2010                         45
UILabel
        • UIView subclass that knows how to draw text

        • Properties include:
            ■ font
            ■ textColor

            ■ shadow (offset & color)

            ■ textAlignment




Tuesday, January 19, 2010                               46
UIImageView
        • UIView that draws UIImages

        • Properties include:
            ■ image
            ■ animatedImages

            ■ animatedDuration

            ■ animatedRepeatCount




        • contentMode property to align and scale image wrt bounds




Tuesday, January 19, 2010                                            47
UIControl
        • UIView with Target-Action event handling

        • Properties include:
            ■ enabled
            ■ selected

            ■ highlighted




        • UIButton: font, title, titleColor, image, backgroundImage
        • UITextField: font, text, placeholder, textColor

        • See UIKit headers for plenty more


Tuesday, January 19, 2010                                             48
View Properties & Animation




Tuesday, January 19, 2010             49
Animating Views
        • What if you want to change layout dynamically?
        • For example, a switch to disclose additional views...




Tuesday, January 19, 2010                                         50
Animating Views
        • What if you want to change layout dynamically?
        • For example, a switch to disclose additional views...




Tuesday, January 19, 2010                                         50
Animating Views
        • What if you want to change layout dynamically?
        • For example, a switch to disclose additional views...




Tuesday, January 19, 2010                                         50
UIView Animations
        • UIView supports a number of animatable properties
            ■   frame, bounds, center, alpha, transform


        • Create “blocks” around changes to animatable properties

        • Animations run asynchronously and automatically




Tuesday, January 19, 2010                                           51
Other Animation Options
        • Additional animation options
            ■ delay before starting
            ■ start at specific time

            ■ curve (ease in/out, ease in, ease out, linear)

            ■ repeat count

            ■ autoreverses (e.g. ping pong back and forth)




Tuesday, January 19, 2010                                      52
View Animation Example
       - (void)showAdvancedOptions {
           // assume polygonView and optionsView
              [UIView beginAnimations:@”advancedAnimations” context:nil];
              [UIView setAnimationDuration:0.3];


              // make optionsView visible (alpha is currently 0.0)
              optionsView.alpha = 1.0;

              // move the polygonView down
              CGRect polygonFrame = polygonView.frame;
              polygonFrame.origin.y += 200;
              polygonView.frame = polygonFrame;


              [UIView commitAnimations];

       }



Tuesday, January 19, 2010                                                   53
Knowing When Animations Finish
        • UIView animations allow for a delegate
          	 	 	 [UIView setAnimationDelegate:myController];


        • myController will have callbacks invoked before and after
                 - (void)animationWillStart:(NSString *)animationID
                         context:(void *)context;

                 - (void)animationDidStop:(NSString *)animationID
                         finished:(NSNumber *)finished
                         context:(void *)context;

        • Can provide custom selectors if desired, for example
                 [UIView setAnimationWillStartSelector:
                                @selector(animationWillStart)];
                 [UIView setAnimationDidStopSelector:
                                @selector(animationDidStop)];



Tuesday, January 19, 2010                                             54
How Does It Work?
        • Is drawRect: invoked repeatedly?
        • Do I have to run some kind of timer in order to drive the
          animation?
        • Is it magic?




Tuesday, January 19, 2010                                             55
Core Animation
        • Hardware accelerated rendering engine

        • UIViews are backed by “layers”

        • -drawRect: results are cached
            ■ Cached results used to render view
            ■ -drawRect: called only when contents change

            ■ Layers drawn from a separate render tree managed by separate

              process


        • Property animations done automatically by manipulating layers


Tuesday, January 19, 2010                                                    56
View Transforms
        • Every view has a transform property
            ■   used to apply scaling, rotation and translation to a view
        • Default “Identity transform”
        • CGAffineTransform structure used to represent transform
        • Use CG functions to create, modify transforms

                CGAffineTransform Functions (just a small example set)
            CGAffineTransformScale (transform, xScale, yScale)
            CGAffineTransformRotate (transform, angle)

            CGAffineTransformTranslate (transform, xDelta, yDelta)



Tuesday, January 19, 2010                                                   57
More Animation Information
        • iPhone OS Programming Guide
            ■   “Modifying Views at Runtime” section
        • Core Animation Programming Guide




Tuesday, January 19, 2010                              58
Assignment 3 Hints




Tuesday, January 19, 2010    59
Saving State Across App Launches
        • NSUserDefaults to read and write prefs & state

        • Singleton object:
               + (NSUserDefaults *)standardUserDefaults;


        • Methods for storing & fetching common types:
               - (int)integerForKey:(NSString *)key;
               - (void)setInteger:(int)value forKey:(NSString *)key;
               			
               - (id)objectForKey:(NSString *)key;
               - (void)setObject:(id)value forKey:(NSString *)key;


        • Find an appropriate time to store and restore your state

Tuesday, January 19, 2010                                              60
Questions?




Tuesday, January 19, 2010   61

Mais conteúdo relacionado

Destaque

03 Custom Classes
03 Custom Classes03 Custom Classes
03 Custom ClassesMahmoud
 
02 Objective C
02 Objective C02 Objective C
02 Objective CMahmoud
 
01 Introduction
01 Introduction01 Introduction
01 IntroductionMahmoud
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View ControllerMahmoud
 
06 View Controllers
06 View Controllers06 View Controllers
06 View ControllersMahmoud
 
Mobile design matters - iOS and Android
Mobile design matters - iOS and AndroidMobile design matters - iOS and Android
Mobile design matters - iOS and AndroidLight Lin
 
Beginning Real World iOS App Development
Beginning Real World iOS App DevelopmentBeginning Real World iOS App Development
Beginning Real World iOS App DevelopmentAndri Yadi
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteachingeteaching
 
Gigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die tryingGigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die tryingAlex Rupérez
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & ArchitectureMassimo Oliviero
 
Top iOS App Development Companies | Mobile App Development Companies - 2017
Top iOS App Development Companies | Mobile App Development Companies - 2017Top iOS App Development Companies | Mobile App Development Companies - 2017
Top iOS App Development Companies | Mobile App Development Companies - 2017Jane Brewer
 
iOS Coding Best Practices
iOS Coding Best PracticesiOS Coding Best Practices
iOS Coding Best PracticesJean-Luc David
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programmingMohamed Ali
 

Destaque (17)

03 Custom Classes
03 Custom Classes03 Custom Classes
03 Custom Classes
 
02 Objective C
02 Objective C02 Objective C
02 Objective C
 
09 Data
09 Data09 Data
09 Data
 
iOS: View Controllers
iOS: View ControllersiOS: View Controllers
iOS: View Controllers
 
01 Introduction
01 Introduction01 Introduction
01 Introduction
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View Controller
 
06 View Controllers
06 View Controllers06 View Controllers
06 View Controllers
 
Mobile design matters - iOS and Android
Mobile design matters - iOS and AndroidMobile design matters - iOS and Android
Mobile design matters - iOS and Android
 
Beginning Real World iOS App Development
Beginning Real World iOS App DevelopmentBeginning Real World iOS App Development
Beginning Real World iOS App Development
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Gigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die tryingGigigo Workshop - Create an iOS Framework, document it and not die trying
Gigigo Workshop - Create an iOS Framework, document it and not die trying
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & Architecture
 
Top iOS App Development Companies | Mobile App Development Companies - 2017
Top iOS App Development Companies | Mobile App Development Companies - 2017Top iOS App Development Companies | Mobile App Development Companies - 2017
Top iOS App Development Companies | Mobile App Development Companies - 2017
 
Architecting iOS Project
Architecting iOS ProjectArchitecting iOS Project
Architecting iOS Project
 
iOS Coding Best Practices
iOS Coding Best PracticesiOS Coding Best Practices
iOS Coding Best Practices
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 

Mais de Mahmoud

مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟Mahmoud
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتكMahmoud
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغيرMahmoud
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمMahmoud
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائقMahmoud
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقريةMahmoud
 
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهمهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهMahmoud
 
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟Mahmoud
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغيرMahmoud
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائقMahmoud
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتكMahmoud
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمMahmoud
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقريةMahmoud
 
Accident Investigation
Accident InvestigationAccident Investigation
Accident InvestigationMahmoud
 
Investigation Skills
Investigation SkillsInvestigation Skills
Investigation SkillsMahmoud
 
Building Papers
Building PapersBuilding Papers
Building PapersMahmoud
 
Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Mahmoud
 
Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Mahmoud
 
A Basic Modern Russian Grammar
A Basic Modern Russian Grammar A Basic Modern Russian Grammar
A Basic Modern Russian Grammar Mahmoud
 

Mais de Mahmoud (20)

مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتك
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغير
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقرية
 
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهمهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
 
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغير
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتك
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقرية
 
Accident Investigation
Accident InvestigationAccident Investigation
Accident Investigation
 
Investigation Skills
Investigation SkillsInvestigation Skills
Investigation Skills
 
Building Papers
Building PapersBuilding Papers
Building Papers
 
Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02
 
Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01
 
A Basic Modern Russian Grammar
A Basic Modern Russian Grammar A Basic Modern Russian Grammar
A Basic Modern Russian Grammar
 
Teams Ar
Teams ArTeams Ar
Teams Ar
 

Último

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 

Último (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 

05 Views

  • 1. CS193P - Lecture 5 iPhone Application Development Views Drawing Animation Tuesday, January 19, 2010 1
  • 2. Announcements • Assignment 1 grades are out. Contact Paul or Dave if you didn’t get yours • Contact Paul or Dave if you need a loaner iPod Touch • Assignments 2A and 2B due Wednesday, 1/20 Tuesday, January 19, 2010 2
  • 3. Questions from Monday? • Model, View, Controller • Interface Builder & Nibs • Delegate ■ Allows one object to act on behalf of another object • Target-Action Tuesday, January 19, 2010 3
  • 4. Today’s Topics • Views • Drawing • Text & Images • Animation Tuesday, January 19, 2010 4
  • 6. View Fundamentals • Rectangular area on screen • Draws content • Handles events • Subclass of UIResponder (event handling class) • Views arranged hierarchically ■ every view has one superview ■ every view has zero or more subviews Tuesday, January 19, 2010 6
  • 7. View Hierarchy - UIWindow • Views live inside of a window • UIWindow is actually just a view ■ adds some additional functionality specific to top level view • One UIWindow for an iPhone app ■ Contains the entire view hierarchy ■ Set up by default in Xcode template project Tuesday, January 19, 2010 7
  • 8. View Hierarchy - Manipulation • Add/remove views in IB or using UIView methods - (void)addSubview:(UIView *)view; - (void)removeFromSuperview; • Manipulate the view hierarchy manually: - (void)insertSubview:(UIView *)view atIndex:(int)index; - (void)insertSubview:(UIView *)view belowSubview:(UIView *)view; - (void)insertSubview:(UIView *)view aboveSubview:(UIView *)view; - (void)exchangeSubviewAtIndex:(int)index withSubviewAtIndex:(int)otherIndex; Tuesday, January 19, 2010 8
  • 9. View Hierarchy - Ownership • Superviews retain their subviews • Not uncommon for views to only be retained by superview ■ Be careful when removing! ■ Retain subview before removing if you want to reuse it • Views can be temporarily hidden theView.hidden = YES; Tuesday, January 19, 2010 9
  • 10. View-related Structures • CGPoint ■ location in space: { x , y } • CGSize ■ dimensions: { width , height } • CGRect ■ location and dimension: { origin , size } Tuesday, January 19, 2010 10
  • 11. Rects, Points and Sizes CGRect (0, 0) x 54 origin CGPoint x 80 80 size y 54 y 144 CGSize width 144 72 height 72 Tuesday, January 19, 2010 11
  • 12. View-related Structure Creation Function Example CGPoint point = CGPointMake (100.0, 200.0); CGPointMake (x, y) point.x = 300.0; point.y = 30.0; CGSize size = CGSizeMake (42.0, 11.0); CGSizeMake (width, height) size.width = 100.0; size.height = 72.0; CGRect rect = CGRectMake (100.0, 200.0, CGRectMake (x, y, 42.0, 11.0); width, height) rect.origin.x = 0.0; rect.size.width = 50.0; Tuesday, January 19, 2010 12
  • 13. UIView Coordinate System ■ Origin in upper left corner ■ y axis grows downwards 0, 0 +x +y Tuesday, January 19, 2010 13
  • 14. UIView Coordinate System ■ Origin in upper left corner ■ y axis grows downwards 0, 0 +x UIView +y Tuesday, January 19, 2010 13
  • 15. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system Tuesday, January 19, 2010 14
  • 16. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system View A Tuesday, January 19, 2010 14
  • 17. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A 400 Tuesday, January 19, 2010 14
  • 18. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 View A bounds: origin: 0, 0 size: 550 x 400 400 Tuesday, January 19, 2010 14
  • 19. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 View A bounds: View B origin: 0, 0 size: 550 x 400 400 Tuesday, January 19, 2010 14
  • 20. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 200, 100 View A bounds: View B origin: 0, 0 size: 550 x 400 400 Tuesday, January 19, 2010 14
  • 21. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 200, 100 200 View A bounds: View B origin: 0, 0 size: 550 x 400 400 250 Tuesday, January 19, 2010 14
  • 22. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 200, 100 200 View A bounds: View B origin: 0, 0 size: 550 x 400 400 250 View B frame: origin: 200, 100 size: 200 x 250 Tuesday, January 19, 2010 14
  • 23. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 200, 100 200 0, 0 View A bounds: View B origin: 0, 0 size: 550 x 400 400 250 View B frame: origin: 200, 100 size: 200 x 250 Tuesday, January 19, 2010 14
  • 24. Location and Size • View’s location and size expressed in two ways ■ Frame is in superview’s coordinate system ■ Bounds is in local coordinate system 0, 0 550 View A frame: View A origin: 0, 0 size: 550 x 400 200, 100 200 0, 0 View A bounds: View B origin: 0, 0 size: 550 x 400 400 250 View B frame: origin: 200, 100 size: 200 x 250 View B bounds: origin: 0, 0 size: 200 x 250 Tuesday, January 19, 2010 14
  • 25. Frame is Computed 200, 100 View A 200 View B 250 Tuesday, January 19, 2010 15
  • 26. Bounds View A 200 0, 0 View B 250 Tuesday, January 19, 2010 16
  • 27. Center View A 200 0, 0 View B 250 Tuesday, January 19, 2010 17
  • 28. Center View A 200 300, 225 0, 0 View B 250 Tuesday, January 19, 2010 17
  • 29. Frame 200, 100 View A 200 300, 225 View B 250 Tuesday, January 19, 2010 18
  • 30. Transform • 45° Rotation View A 0, 0 300, 225 20 Vi 25 0 ew 0 B Tuesday, January 19, 2010 19
  • 31. Frame • The smallest rectangle in the superview’s coordinate system that fully encompasses the view itself 140, 65 320 View A 0, 0 300, 225 20 Vi 25 0 ew 0 320 B Tuesday, January 19, 2010 20
  • 32. Frame and Bounds • Which to use? ■ Usually depends on the context • If you are using a view, typically you use frame • If you are implementing a view, typically you use bounds • Matter of perspective ■ From outside it’s usually the frame ■ From inside it’s usually the bounds • Examples: ■ Creating a view, positioning a view in superview - use frame ■ Handling events, drawing a view - use bounds Tuesday, January 19, 2010 21
  • 34. Where do views come from? • Commonly Interface Builder • Drag out any of the existing view objects (buttons, labels, etc) • Or drag generic UIView and set custom class Tuesday, January 19, 2010 23
  • 35. Manual Creation • Views are initialized using -initWithFrame: CGRect frame = CGRectMake(0, 0, 200, 150); UIView *myView = [[UIView alloc] initWithFrame:frame]; • Example: CGRect frame = CGRectMake(20, 45, 140, 21); UILabel *label = [[UILabel alloc] initWithFrame:frame]; [window addSubview:label]; [label setText:@”Number of sides:”]; [label release]; // label now retained by window Tuesday, January 19, 2010 24
  • 36. Defining Custom Views • Subclass UIView • For custom drawing, you override: - (void)drawRect:(CGRect)rect; • For event handling, you override: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; Tuesday, January 19, 2010 25
  • 38. - (void)drawRect:(CGRect)rect • -[UIView drawRect:] does nothing by default ■ If not overridden, then backgroundColor is used to fill • Override - drawRect: to draw a custom view ■ rect argument is area to draw • When is it OK to call drawRect:? Tuesday, January 19, 2010 27
  • 39. Be Lazy • drawRect: is invoked automatically ■ Don’t call it directly! • Being lazy is good for performance • When a view needs to be redrawn, use: - (void)setNeedsDisplay; • For example, in your controller: - (void)setNumberOfSides:(int)sides { numberOfSides = sides; [polygonView setNeedsDisplay]; } Tuesday, January 19, 2010 28
  • 40. CoreGraphics and Quartz 2D • UIKit offers very basic drawing functionality UIRectFill(CGRect rect); UIRectFrame(CGRect rect); • CoreGraphics: Drawing APIs • CG is a C-based API, not Objective-C • CG and Quartz 2D drawing engine define simple but powerful graphics primitives ■ Graphics context ■ Transformations ■ Paths ■ Colors ■ Fonts ■ Painting operations Tuesday, January 19, 2010 29
  • 41. Graphics Contexts • All drawing is done into an opaque graphics context • Draws to screen, bitmap buffer, printer, PDF, etc. • Graphics context setup automatically before invoking drawRect: ■ Defines current path, line width, transform, etc. ■ Access the graphics context within drawRect: by calling (CGContextRef)UIGraphicsGetCurrentContext(void); ■ Use CG calls to change settings • Context only valid for current call to drawRect: ■ Do not cache a CGContext! Tuesday, January 19, 2010 30
  • 42. CG Wrappers • Some CG functionality wrapped by UIKit • UIColor ■ Convenience for common colors ■ Easily set the fill and/or stroke colors when drawing UIColor *redColor = [UIColor redColor]; [redColor set]; // drawing will be done in red • UIFont ■ Access system font ■ Get font by name UIFont *font = [UIFont systemFontOfSize:14.0]; [myLabel setFont:font]; Tuesday, January 19, 2010 31
  • 43. Simple drawRect: example • Draw a solid color and shape - (void)drawRect:(CGRect)rect { CGRect bounds = [self bounds]; [[UIColor grayColor] set]; UIRectFill (bounds); CGRect square = CGRectMake (10, 10, 50, 100); [[UIColor redColor] set]; UIRectFill (square); [[UIColor blackColor] set]; UIRectFrame (square); } Tuesday, January 19, 2010 32
  • 44. Simple drawRect: example • Draw a solid color and shape - (void)drawRect:(CGRect)rect { CGRect bounds = [self bounds]; [[UIColor grayColor] set]; UIRectFill (bounds); CGRect square = CGRectMake (10, 10, 50, 100); [[UIColor redColor] set]; UIRectFill (square); [[UIColor blackColor] set]; UIRectFrame (square); } Tuesday, January 19, 2010 32
  • 45. Drawing More Complex Shapes • Common steps for drawRect: are ■ Get current graphics context ■ Define a path ■ Set a color ■ Stroke or fill path ■ Repeat, if necessary Tuesday, January 19, 2010 33
  • 46. Paths • CoreGraphics paths define shapes • Made up of lines, arcs, curves and rectangles • Creation and drawing of paths are two distinct operations ■ Define path first, then draw it Tuesday, January 19, 2010 34
  • 47. CGPath • Two parallel sets of functions for using paths ■ CGContext “convenience” throwaway functions ■ CGPath functions for creating reusable paths CGContext CGPath CGContextMoveToPoint CGPathMoveToPoint CGContextAddLineToPoint CGPathAddLineToPoint CGContextAddArcToPoint CGPathAddArcToPoint CGContextClosePath CGPathCloseSubPath And so on and so on . . . Tuesday, January 19, 2010 35
  • 48. Simple Path Example - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor grayColor] set]; UIRectFill ([self bounds]); CGContextBeginPath (context); CGContextMoveToPoint (context, 75, 10); CGContextAddLineToPoint (context, 10, 150); CGContextAddLineToPoint (context, 160, 150); CGContextClosePath (context); [[UIColor redColor] setFill]; [[UIColor blackColor] setStroke]; CGContextDrawPath (context, kCGPathFillStroke); } Tuesday, January 19, 2010 36
  • 49. Simple Path Example - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor grayColor] set]; UIRectFill ([self bounds]); CGContextBeginPath (context); CGContextMoveToPoint (context, 75, 10); CGContextAddLineToPoint (context, 10, 150); CGContextAddLineToPoint (context, 160, 150); CGContextClosePath (context); [[UIColor redColor] setFill]; [[UIColor blackColor] setStroke]; CGContextDrawPath (context, kCGPathFillStroke); } Tuesday, January 19, 2010 36
  • 50. More Drawing Information • UIView Class Reference • CGContext Reference • “Quartz 2D Programming Guide” • Lots of samples in the iPhone Dev Center Tuesday, January 19, 2010 37
  • 51. Images & Text Tuesday, January 19, 2010 38
  • 52. UIImage • UIKit class representing an image • Creating UIImages: ■ Fetching image in application bundle ■ Use +[UIImage imageNamed:(NSString *)name] ■ Include file extension in file name, e.g. @”myImage.jpg” ■ Read from file on disk ■ Use -[UIImage initWithContentsOfFile:(NSString *)path] ■ From data in memory ■ Use -[UIImage initWithData:(NSData *)data] Tuesday, January 19, 2010 39
  • 53. Creating Images from a Context • Need to dynamically generate a bitmap image • Same as drawing a view • General steps ■ Create a special CGGraphicsContext with a size ■ Draw ■ Capture the context as a bitmap ■ Clean up Tuesday, January 19, 2010 40
  • 54. Bitmap Image Example - (UIImage *)polygonImageOfSize:(CGSize)size { UIImage *result = nil; UIGraphicsBeginImageContext (size); // call your drawing code... result = UIGraphicsGetImageFromCurrentContext(); UIGraphicsEndImageContext(); return result; } Tuesday, January 19, 2010 41
  • 55. Getting Image Data • Given UIImage, want PNG or JPG representation NSData *UIImagePNGRepresentation (UIImage * image); NSData *UIImageJPGRepresentation (UIImage * image); • UIImage also has a CGImage property which will give you a CGImageRef to use with CG calls Tuesday, January 19, 2010 42
  • 56. Drawing Text & Images • You can draw UIImages in -drawRect: - [UIImage drawAtPoint:(CGPoint)point] - [UIImage drawInRect:(CGRect)rect] - [UIImage drawAsPatternInRect:(CGRect)rect] • You can draw NSString in -drawRect: - [NSString drawAtPoint:(CGPoint)point withFont:(UIFont *)font] Tuesday, January 19, 2010 43
  • 57. Drawing Text & Images • You can draw UIImages in -drawRect: - [UIImage drawAtPoint:(CGPoint)point] - [UIImage drawInRect:(CGRect)rect] - [UIImage drawAsPatternInRect:(CGRect)rect] • You can draw NSString in -drawRect: - [NSString drawAtPoint:(CGPoint)point withFont:(UIFont *)font] But there is a better way! Tuesday, January 19, 2010 43
  • 58. Text, Images, and UIKit views Tuesday, January 19, 2010 44
  • 59. Constructing Views • How do I implement this? Tuesday, January 19, 2010 45
  • 60. Constructing Views • How do I implement this? • Goal ■ PolygonView that displays shape as well as name Tuesday, January 19, 2010 45
  • 61. Constructing Views • How do I implement this? • Goal ■ PolygonView that displays shape as well as name • Initial thought ■ Have PolygonView draw the text ■ Inefficient when animating Tuesday, January 19, 2010 45
  • 62. Constructing Views • How do I implement this? • Goal ■ PolygonView that displays shape as well as name • Initial thought ■ Have PolygonView draw the text ■ Inefficient when animating • Instead use UILabel! ■ Tastes great ■ Less filling Tuesday, January 19, 2010 45
  • 63. UILabel • UIView subclass that knows how to draw text • Properties include: ■ font ■ textColor ■ shadow (offset & color) ■ textAlignment Tuesday, January 19, 2010 46
  • 64. UIImageView • UIView that draws UIImages • Properties include: ■ image ■ animatedImages ■ animatedDuration ■ animatedRepeatCount • contentMode property to align and scale image wrt bounds Tuesday, January 19, 2010 47
  • 65. UIControl • UIView with Target-Action event handling • Properties include: ■ enabled ■ selected ■ highlighted • UIButton: font, title, titleColor, image, backgroundImage • UITextField: font, text, placeholder, textColor • See UIKit headers for plenty more Tuesday, January 19, 2010 48
  • 66. View Properties & Animation Tuesday, January 19, 2010 49
  • 67. Animating Views • What if you want to change layout dynamically? • For example, a switch to disclose additional views... Tuesday, January 19, 2010 50
  • 68. Animating Views • What if you want to change layout dynamically? • For example, a switch to disclose additional views... Tuesday, January 19, 2010 50
  • 69. Animating Views • What if you want to change layout dynamically? • For example, a switch to disclose additional views... Tuesday, January 19, 2010 50
  • 70. UIView Animations • UIView supports a number of animatable properties ■ frame, bounds, center, alpha, transform • Create “blocks” around changes to animatable properties • Animations run asynchronously and automatically Tuesday, January 19, 2010 51
  • 71. Other Animation Options • Additional animation options ■ delay before starting ■ start at specific time ■ curve (ease in/out, ease in, ease out, linear) ■ repeat count ■ autoreverses (e.g. ping pong back and forth) Tuesday, January 19, 2010 52
  • 72. View Animation Example - (void)showAdvancedOptions { // assume polygonView and optionsView [UIView beginAnimations:@”advancedAnimations” context:nil]; [UIView setAnimationDuration:0.3]; // make optionsView visible (alpha is currently 0.0) optionsView.alpha = 1.0; // move the polygonView down CGRect polygonFrame = polygonView.frame; polygonFrame.origin.y += 200; polygonView.frame = polygonFrame; [UIView commitAnimations]; } Tuesday, January 19, 2010 53
  • 73. Knowing When Animations Finish • UIView animations allow for a delegate [UIView setAnimationDelegate:myController]; • myController will have callbacks invoked before and after - (void)animationWillStart:(NSString *)animationID context:(void *)context; - (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context; • Can provide custom selectors if desired, for example [UIView setAnimationWillStartSelector: @selector(animationWillStart)]; [UIView setAnimationDidStopSelector: @selector(animationDidStop)]; Tuesday, January 19, 2010 54
  • 74. How Does It Work? • Is drawRect: invoked repeatedly? • Do I have to run some kind of timer in order to drive the animation? • Is it magic? Tuesday, January 19, 2010 55
  • 75. Core Animation • Hardware accelerated rendering engine • UIViews are backed by “layers” • -drawRect: results are cached ■ Cached results used to render view ■ -drawRect: called only when contents change ■ Layers drawn from a separate render tree managed by separate process • Property animations done automatically by manipulating layers Tuesday, January 19, 2010 56
  • 76. View Transforms • Every view has a transform property ■ used to apply scaling, rotation and translation to a view • Default “Identity transform” • CGAffineTransform structure used to represent transform • Use CG functions to create, modify transforms CGAffineTransform Functions (just a small example set) CGAffineTransformScale (transform, xScale, yScale) CGAffineTransformRotate (transform, angle) CGAffineTransformTranslate (transform, xDelta, yDelta) Tuesday, January 19, 2010 57
  • 77. More Animation Information • iPhone OS Programming Guide ■ “Modifying Views at Runtime” section • Core Animation Programming Guide Tuesday, January 19, 2010 58
  • 78. Assignment 3 Hints Tuesday, January 19, 2010 59
  • 79. Saving State Across App Launches • NSUserDefaults to read and write prefs & state • Singleton object: + (NSUserDefaults *)standardUserDefaults; • Methods for storing & fetching common types: - (int)integerForKey:(NSString *)key; - (void)setInteger:(int)value forKey:(NSString *)key; - (id)objectForKey:(NSString *)key; - (void)setObject:(id)value forKey:(NSString *)key; • Find an appropriate time to store and restore your state Tuesday, January 19, 2010 60