Things wot I learnt from Stanford – iPad & iPhone App Development – Fall 2011 – Lecture 5

Protocols and Gestures

When rotated, the frame of all sub views in your controller’s view will be adjusted based on their “struts & springs”.

You define the struts & springs in the Interface Builder:

Slide: Struts and Springs

Defining Struts and Springs in Interface Builder.

The outer, white rectangle in the preview represents the superview. The inner, red box is the view you’re defining your struts and springs for.

By default, after a rotation, drawRect is NOT called – instead the “bits” of any custom drawing in your view will be stretched or squished or moved according to a UIView @property contentMode:

@property (nonatomic) UIViewContentMode contentMode;

There are many possible values for contentMode all prefixed UIViewContentMode including Left, Right, Top, Bottom, BottomLeft, BottomRight, TopLeft and TopRight

These modes have a similar effect to struts and springs i.e. they move your bits to that location but the contentMode is actually applied AFTER any struts and springs.

There are also some content modes which describe how you want your bits to scale UIViewContentModeScaleToFill, UIViewContentModeAspectFill, UIViewContentModeAspectFit.

UIViewContentModeScaleToFill is the default and is the reason why, if you don’t specify a mode, any drawings can become elongated or squished into a different aspect ratio – like your gran’s new TV.

contentMode UIViewContentModeRedraw ensures drawRect is called. This is usually what you would want if you have custom drawing.

There is another @property:

@property (nonatomic) CGRect contentStretch

This allows you to control which bits get stretched and which don’t. This is useful for example if you have a button where you’d like the middle part stretched but the ends to stay the same.

Note that you can set the contentMode in code usually when your view is initialized, or you can simply set it using a drop down in Interface Builder – select your view and navigate to the Attributes Inspector – the list is labelled “Mode”.

Storyboards and UIView Initialization

Warning: when a view is initialized from a nib file or Storyboard, initWithFrame (the designated initializer) DOES NOT GET CALLED. Instead, awakeFromNib is called. If you have a habit of putting setup code in initWithFrame you need to be aware if this. Move your setup code into a separate method and call from both as per the slide.

Warning: awakeFromNib

Call setup() from Warning: awakeFromNib: AND initWithFrame:

Note it’s neater to put your setup stuff in property setters or getters rather than doing this. If you’re the lazy kind, you could also put it in viewDidLoad and avoid the issue altogether (depending on what your setup does).


It is considered good practice to always include <NSObject> as a required protocol in any protocol definition. This ensures that only descendants of NSObject can use your protocol since descendants of NSObject will, by inheritance, handle the <NSObject> protocol. Since we mainly work with NSObject descendants in Objective-C this could also be considered a waste of typing unless you’re a pedant – but we all are aren’t we? 😉

Protocols - Syntax

The syntax for defining Protocols

Protocols are defined in a header (.h) file.

A Protocol can be the only thing in a standalone header file – handy for sharing between many objects. Often though a Protocol will be in the header file of the class that wants other classes to implement it. For example the UIScrollViewDelegate Protocol is defined in UIScrollView.h along with the definition for the UIScrollView itself.

You can refer to an object that implements a protocol using the <Protocol> specifier e.g.:

id <Foo> obj = [[MyClass alloc]init];

This allows the compiler to alert you with warnings if you assign any object that doesn’t implement <Foo>. You can also use this in arguments and @property declarations (see slide).

Declaring Protocol Implementers

Declaring Protocol Implementers for the sake of the compiler.

A view should never need to know the class of its controller.

The most common use of a Protocol is for delegates. A delegate or dataSource is almost always defined as a weak @property.

@property (nonatomic, weak) id <UISomeObjectDelegate> delegate;

This is common sense really since the object serving as a delegate will usually outlive the object doing the delegating – especially when the delegator is a view (such as UIScrollView) since the delegate is that view’s controller. Controllers always create and clean up their views. Views are just their minions. They are Gaga’s little monsters.

A dataSource is just like a delegate in that we’re delegating the provision of data. Views often have a dataSource delegate as they cannot own their data.

Gesture Recognizers

Gesture recognizers are usually added by the controller and handled by the view – adding the gesture recognizer is the equivalent to “switching it on”. Views often “know” what to do with the gesture e.g. “pinch”. If a view doesn’t make sense without the gesture then it may even add its own gesture recognizer as well as handling it (e.g. a UIScrollView). Even in this case, the handler may instead be handled by the controller if you want to handle things differently – e.g. a gesture that effects the model since the view should not modify the model directly.

The initWithTarget: argument of a gesture recognizer actually specifies the gesture handler NOT the object on which the gesture will operate – that is specified by the receiver of the addGestureRecognizer message.

A reference to the gesture recognizer itself is sent to the handler so it can be examined for its state. Every gesture recognizer has a readonly “state” property of type UIGestureRecognizerState.

The Initial value of state is “Possible”, another value is “Recognized”. Discrete gestures such as tap can go directly to this state. Continuous gestures like pan can also have states of “Began”, “Changed” and “Ended”. At any time, the state can change to “Failed”, for example if a phone call interrupts a gesture, or “Cancelled” if the recognizer realizes its not a gesture after all.

Handling the pan gesture (slide)

Handling the pan gesture

A Nice Tip

If your custom view has a writable property, the value of which can effect any displayed, custom drawing (e.g. a “scale” property) a common pattern is to call [self setNeedsDisplay] in the property setter. This queues up a call to drawRect: which will redraw your view with the new property value – neato!! TIP: Wrap this in a check which makes sure that setNeedsDisplay is only called if the property value has actually changed. Calls to drawRect can be expensive so shouldn’t be done if not necessary!

Tip: Calling setNeedsDisplay in your setter (slide)

Tip: Calling setNeedsDisplay in your setter


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s