Stanford CS193p: Developing Applications For iOS Spring 2016
Stanford CS193p: Developing Applications For iOS Spring 2016
CS193p
Spring 2016
Today
Views
Custom Drawing
Demo
FaceView
CS193p
Spring 2016
Views
A view (i.e. UIView subclass) represents a rectangular area
Defines a coordinate space
For drawing
And for handling touch events
Hierarchical
A view has only one superview … var superview: UIView?
But it can have many (or zero) subviews … var subviews: [UIView]
The order in the subviews array matters: those later in the array are on top of those earlier
A view can clip its subviews to its own bounds or not (the default is not to)
UIWindow
The UIView at the very, very top of the view hierarchy (even includes status bar)
Usually only one UIWindow in an entire iOS application … it’s all about views, not windows
CS193p
Spring 2016
Views
The hierarchy is most often constructed in Xcode graphically
Even custom views are usually added to the view hierarchy using Xcode
CS193p
Spring 2016
Initializing a UIView
As always, try to avoid an initializer if possible
But having one in UIView is slightly more common than having a UIViewController initializer
Spring 2016
Initializing a UIView
Another alternative to initializers in UIView …
awakeFromNib() // this is only called if the UIView came out of a storyboard
This is not an initializer (it’s called immediately after initialization is complete)
All objects that inherit from NSObject in a storyboard are sent this
Order is not guaranteed, so you cannot message any other objects in the storyboard here
CS193p
Spring 2016
Coordinate System Data Structures
CGFloat
Always use this instead of Double or Float for anything to do with a UIView’s coordinate system
You can convert to/from a Double or Float using initializers, e.g., let cfg = CGFloat(aDouble)
CGPoint
Simply a struct with two CGFloats in it: x and y.
var point = CGPoint(x: 37.0, y: 55.2)
point.y -= 30
point.x += 20.0
CGSize
Also a struct with two CGFloats in it: width and height.
var size = CGSize(width: 100.0, height: 50.0)
size.width += 42.5
size.height += 75
CS193p
Spring 2016
Coordinate System Data Structures
CGRect
A struct with a CGPoint and a CGSize in it …
struct CGRect {
var origin: CGPoint
var size: CGSize
}
let rect = CGRect(origin: aCGPoint, size: aCGSize) // there are other inits as well
CS193p
Spring 2016
increasing x
View Coordinate System
(0,0)
(500, 35)
CS193p
Spring 2016
bounds vs frame
Use frame and/or center to position a UIView
These are never used to draw inside a view’s coordinate system
You might think frame.size is always equal to bounds.size, but you’d be wrong …
140 Views can be rotated (and scaled and translated)
, 65
View A
30 320
0, View B’s bounds = ((0,0),(200,250))
22 0
5 5 0,
View B’s frame = ((140,65),(320,320))
20
2
0
0
View B’s center = (300,225)
Vi
ew View B’s middle in its own coordinates is …
320 B (bounds.midX, bounds.midY) = (100, 125)
CS193p
Spring 2016
Creating Views
Most often your views are created via your storyboard
Xcode’s Object Palette has a generic UIView you can drag out
After you do that, you must use the Identity Inspector to changes its class to your subclass
Example
// assuming this code is in a UIViewController
let labelRect = CGRect(x: 20, y: 20, width: 100, height: 50)
let label = UILabel(frame: labelRect) // UILabel is a subclass of UIView
label.text = “Hello”
view.addSubview(label)
Hello CS193p
Spring 2016
Custom Views
When would I create my own UIView subclass?
I want to do some custom drawing on screen
I need to handle touch events in a special way (i.e. different than a button or slider does)
We’ll talk about handling touch events in a bit. First we’ll focus on drawing.
Spring 2016
Custom Views
So how do I implement my drawRect?
You can use a C-like (non object-oriented) API called Core Graphics
Or you can use the object-oriented UIBezierPath class (which is how we’ll do it)
CS193p
Spring 2016
Custom Views
So how do I implement my drawRect?
You can use a C-like (non object-oriented) API called Core Graphics
Or you can use the object-oriented UIBezierPath class (which is how we’ll do it)
UIBezierPath
Same as above, but captures all the drawing with a UIBezierPath instance
UIBezierPath automatically draws in the “current” context (drawRect sets this up for you)
UIBezierPath has methods to draw (lineto, arcs, etc.) and set attributes (linewidth, etc.)
Use UIColor to set stroke and fill colors
UIBezierPath has methods to stroke and/or fill
CS193p
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
CS193p
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
CS193p
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
CS193p
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
CS193p
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
CS193p
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
Spring 2016
Defining a Path
Create a UIBezierPath
let path = UIBezierPath()
Spring 2016
Drawing
You can also draw common shapes with UIBezierPath
let roundRect = UIBezierPath(roundedRect: aCGRect, cornerRadius: aCGFloat)
let oval = UIBezierPath(ovalInRect: aCGRect)
… and others
Hit detection
func containsPoint(CGPoint) -> Bool // returns whether the point is inside the path
The path must be closed. The winding rule can be set with usesEvenOddFillRule property.
Etc.
Lots of other stuff. Check out the documentation.
CS193p
Spring 2016
UIColor
Colors are set using UIColor
There are type methods for standard colors, e.g. let green = UIColor.greenColor()
You can also create them from RGB, HSB or even a pattern (using UIImage)
CS193p
Spring 2016
View Transparency
What happens when views overlap and have transparency?
As mentioned before, subviews list order determines who is in front
Lower ones (earlier in the array) can “show through” transparent views on top of them
Transparency is not cheap, by the way, so use it wisely
CS193p
Spring 2016
Drawing Text
Usually we use a UILabel to put text on screen
But there are certainly occasions where we want to draw text in our drawRect
CS193p
Spring 2016
Attributed String
Setting attributes on an attributed string
func setAttributes(attributes: Dictionary, range: NSRange)
func addAttributes(attributes: Dictionary, range: NSRange)
Warning! This is a pre-Swift API. NSRange is not a Range.
And indexing into the string is using old-style indexing (not String.Index).
Attributes
NSForegroundColorAttributeName : UIColor
NSStrokeWidthAttributeName : CGFloat
NSFontAttributeName : UIFont
See the documentation under NSAttributedString(NSStringDrawing) for (many) more.
CS193p
Spring 2016
Fonts
Fonts in iOS are very important to get right
CS193p
Spring 2016
Fonts
The absolutely best way to get a font in code
Get preferred font for a given text style (e.g. body, etc.) using this UIFont type method …
class func preferredFontForTextStyle(UIFontTextStyle) -> UIFont
Some of the styles (see UIFontDescriptor documentation for more) …
UIFontTextStyle.Headline
UIFontTextStyle.Body
UIFontTextStyle.Footnote
Spring 2016
Drawing Images
There is a UILabel-equivalent for images
UIImageView
But, again, you might want to draw the image inside your drawRect …
You can also create one from files in the file system
(But we haven’t talked about getting at files in the file system … anyway …)
let image: UIImage? = UIImage(contentsOfFile: aString)
let image: UIImage? = UIImage(data: anNSData) // raw jpg, png, tiff, etc. image data
Spring 2016
Drawing Images
Once you have a UIImage, you can blast its bits on screen
let image: UIImage = …
image.drawAtPoint(aCGPoint) // the upper left corner of the image put at aCGPoint
image.drawInRect(aCGRect) // scales the image to fit aCGRect
image.drawAsPatternInRect(aCGRect) // tiles the image into aCGRect
CS193p
Spring 2016
Redraw on bounds change?
By default, when a UIView’s bounds changes, there is no redraw
Instead, the “bits” of the existing image are scaled to the new bounds size
UIViewContentMode
Don’t scale the view, just place it somewhere …
.Left/.Right/.Top/.Bottom/.TopRight/.TopLeft/.BottomRight/.BottomLeft/.Center
Scale the “bits” of the view …
.ScaleToFill/.ScaleAspectFill/.ScaleAspectFit // .ScaleToFill is the default
Redraw by calling drawRect again (costly, but for certain content, better results) …
.Redraw
CS193p
Spring 2016