---
title: "#151: UIView B-sides  📼"
url: https://littlebitesofcocoa.com/151-uiview-b-sides
author: Jake Marsh
date: 2015-12-21
published: 2015-12-21
topics: ["UIKit","B-sides"]
description: "Today we'll begin looking at some lesser-known functionality inside UIKit. Some of these may be old news, but hopefully not all are."
---

# #151: UIView B-sides  📼

By Jake Marsh, December 21, 2015. HTML: https://littlebitesofcocoa.com/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.

``` swift
class ContainerView : UIView {
  override func didAddSubview(subview: UIView) {
    super.didAddSubview(subview)

    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**: 

``` swift
view.endEditing(true)
```

## 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**:

``` swift
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**:

``` swift
view.backgroundColor = UIColor.redColor()
view.maskView = UIImageView(image: UIImage(named: "vader"))
```

<img src="https://media.littlebitesofcocoa.com/bite-assets/151-uiview-b-sides-masked.png" style="max-width: 93px;" />
