Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.


#151: UIView B-sides πŸ“Ό


Today we'll begin looking at some lesser-known functionality inside UIKit. Some of these may be old news, but hopefully not all are.

We'll start with UIView. Let's flip it over and see what kind of b-side treasures we can find:

Subview Callbacks

We can override functions like didAddSubview(subview:) and willRemoveSubview(subview:) in our UIView subclasses. With this, we can take some action when subviews are added/removed.

class ContainerView : UIView {
  override func didAddSubview(subview: UIView) {

    subview.frame = calculateFrame(subview)

Resigning First Responder

An oldie, but a goodie. We can use the endEditing(force:) function to ask (or force) a view or any text fields inside it to resign as the first responder:


Custom Layer Class

We can specify a custom CALayer subclass for our UIView subclasses by overriding the layerClass function. This is great if our view needs to use CATiledLayer to scroll lots of content, or when building a camera preview view:

class CameraPreviewView : UIView {
  override class func layerClass() -> AnyClass {
    return AVCaptureVideoPreviewLayer.self

Easy Masking

We can "mask" a view using the alpha channel of another view by setting it to the maskView property:

backgroundColor = UIColor.redColor()
maskView = UIImageView(image: UIImage(named: "vader"))