The bits about view in iOS:
- View is an instance of UIView or one of its subclass (e.g. UIScrollView UILabel…)
- View knows how to draw itself (e.g. drawInRect)
- View handles events (e.g. touches, value changes)
- View exists within a hierarchy of views. (root view is app’s window)
Views have their own hierarchy:
- Each view in the hierarchy, renders itself to its layer, an instance of CALayer
- The layers of all the views are composited together to form a complete view
- When you add a view as subview of another view, the superview and subviews properties are automatically established
- Classes like
UIButton
,UILabel
already know how to draw themselves to their layers
So how to create view programmatically:
- You create your own view class inherent from UIView
- initWithFrame: is designated initializer
- drawRect: is for custom drawing
- To create a view, you need to get its frame
- A frame specifies the view’s size and its position relative to its superview, and it’s always in a rectangle model.
- Steps for creating a view :
- Specify the view’s frame
- Init an instance of view
- configure the view instance
- add view instance as subview
How to do customized view:
- UIView subclasses override drawRect: to perform custom drawing. e.g. the drawRect: for UILabel draw text on screen
- To override drawRect, you need to get the bounds
- bounds is a view’s rectangle in its own coordinate system
- frame is the same rectangle in its superview’s coordinate system
- Steps for creating a custom view in drawRect:
- Specify the bounds of view
- Specify necessary geometry variables for building UIBezierPath
- Init an instance of UIBezierPath
- Call appropriate drawing API in UIBezierPath
- Draw the line
Event Handler & Redrawing:
- When user touches a view, the view is sent the message touchesBegan:withEvent:
- It’s a view’s event handler in the run loop
When an app is launched, it starts a run loop, or run lifecycle. Its job is to listen for events, such as touch. When an event occurs, it finds the appropriate handler methods for event. Once finished, control returns to the run loop.
- When run loop regains control, it checks a list of “dirty views” - views that need to be re-rendered
- Then run loop then sends the drawRect: message to those “dirty views”
- To get a view on the re-rendered lists, you must send view the message setNeedDisplay
Reference
- Stanford iOS 7 development
- Mac Developer Library
- Big Nerd Ranch