The Digital Tip of the week will help you set actions for when a UIView is instantiated or disappears. Sometimes I build reusable UIView subclasses to use anywhere in my app. Sometimes I want to associate some behavior when these views are instantiated (i.e: added as subview to a visible view) or disappear (i.e: they are removed from their parent’s view). In UIViewController, you have viewWillAppear/viewWillDisappear, but what can we use in UIView? The answer is willMove:toSuperview: and removeFromSuperView:.

I use these methods specially when I want the view to be aware of notifications.

let myNotificationName = Notification.Name(rawValue: "...")

override func willMove(toSuperview newSuperview: UIView?) {
   super.willMove(toSuperview: newSuperview)
 
   NotificationCenter.default.addObserver(forName: myNotificationName, object: nil, queue: nil) { (notification) in
      if let notificationData = notification.object as? String {
         // ... do something useful with the notification.
      } else { // fallback }
  }
}

override func removeFromSuperview() {
   super.removeFromSuperview()
   NotificationCenter.default.removeObserver(self)
}