VAAA VAAA - 1 year ago 35
Swift Question

How to expose an event from UIView to UIViewController

I have a UIView with the following code:

import UIKit

class ServiceAuthHeaderViewController: UIView {

@IBOutlet var lblHeaderTitle: UILabel!
@IBOutlet var btnAddService: UIButton!

class func instanceFromNib() -> UIView {
return UINib(nibName: "ServiceAuthHeaderView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView

@IBAction func onAddService(sender: AnyObject) {
// I want other UIViewControllers to know when this event ocurrs


Now I have a
where I create an instance of the UIView:

var headerView = ServiceAuthHeaderViewController.instanceFromNib()
headerView. // here I want to attach the onAddService event.

Any clue on how to do that?

Appreciate it

Answer Source

Beside delegate and callbacks like what suggested by @fiks, you can also just simply use add target.

Step 1: change the following to return a ServiceAuthHeaderView instead of a UIView so that you can access its IBOutlet. I renamed it to ServiceAuthHeaderView from ServiceAuthHeaderViewController as this is subclassing UIView.

class func instanceFromNib() -> ServiceAuthHeaderView {
    return UINib(nibName: "ServiceAuthHeaderView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! ServiceAuthHeaderView

Step 2: In your parent that subclass UIViewController, add the btnAddService target in viewDidLoad

class ServiceAuthViewController: UIViewController {

  override func viewDidLoad() {
      let headerView = ServiceAuthHeaderView.instanceFromNib()
      headerView.btnAddService.addTarget(self, action: #selector(ServiceAuthViewController.btnAddServicePressed(_:)), forControlEvents: .TouchUpInside)

Step 3: Create the target action that you entered in the selector and do what you need when the button is pressed inside it.

func btnAddServicePressed(button: UIButton) {
    print("Code for button pressed should be place here")