0

UIView

import UIKit

class TridHeaderBar: UIView {


    @IBAction func btnClick(_ sender: Any) {

    }

}

I would like to go a ViewController from this UIView. I have tried below code

let ctrl = FirstViewController()
self.present(ctrl, animated: true, completion: nil)
Kishan Bhatiya
  • 2,175
  • 8
  • 14
  • Possible duplicate. Better look this answer: https://stackoverflow.com/a/15623730/1659566 – Asike Mar 02 '20 at 11:43

2 Answers2

4

You can use various methods to reach your goal, one of them(and one the best) is use delegation.

So first you need to define your delegate:

protocol MYViewDelegate: class {
  func buttonTap(sender: MYView)
}

Then in your view:

class MyView: UIView {
    weak var delegate: MYViewDelegate?

    @IBAction func btnClick(_ sender: Any) {
        delegate?.buttonTap(sender: self)
    }
}

Now you set the parent view controller where you custom view as delegate of you custom view and the job is done.

class MYParentViewController: UIViewController {
    @IBOutlet var myCustomView: MyView!

    override func viewDidLoad() {
       super.viewDidLoad()
       myCustomView.delegate = self
    }
}

extension MYParentViewController: MYViewDelegate {
    func buttonTapped(sender: MYView) {
       let ctrl = FirstViewController()
       self.present(ctrl, animated: true, completion: nil)
    }
}
Daljeet
  • 1,573
  • 2
  • 20
  • 40
Alastar
  • 1,284
  • 1
  • 8
  • 14
1

You can use Callback function also to get tap action on your parrentViewController:

1) Declare callback function into your view:

var callback:(() -> Void)?

You can also pass any value from your view like (var callback:((String) -> Void)?). I take string here you can pass as you want.

and in button action call this function like this (callback?("i am passing string here"))

2) Call this function in your IBAction of button:

@IBAction func btnClick(_ sender: Any) {
     callback?()
}

3) Write callback function closure in your parrentViewControler:

class ParentViewController: UIViewController {
    @IBOutlet var myCustomView: MyView!

    override func viewDidLoad() {
       super.viewDidLoad()
       viewTapped()
    }

   func viewTapped() {
      myCustomView.callback = { [unowned self] 
          //you will get button tap action here
          let ctrl = FirstViewController()
          self.present(ctrl, animated: true, completion: nil)
      }
   }
}
urvashi koladiya
  • 168
  • 1
  • 11