How to navigate from custom view to contoller?

216 Views Asked by At

*This is my custom view. I have a button "nextButton" . I cant navigate to new viewcontoller because xcode has error "Value of type 'CustomView' has no member 'navigationController". How can i fix?

class CustomView : UIView {


var nextButton : UIButton = {

    let button = UIButton(frame: CGRect(x: 130, y: 190, width: 100, height: 50))
      button.backgroundColor = .systemGreen
      button.setTitle("Next", for: .normal)
    button.addTarget(CustomView.self, action: #selector(nextButtonpressed), for: .touchUpInside)


return button } ()



@objc  func nextButtonpressed() {
let detailVC = ViewController()
self.navigationController.pushViewController(detailVC, animated: true)

}

class AddViewController: UIViewController {

var dimmedBaclroundView : UIView = {
    let view = UIView()
    
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
    return view
}()

lazy var CView = CustomView { [weak self] in
    guard let self = self else {return}
    self.dismiss(animated: true, completion:  nil)
    
}
1

There are 1 best solutions below

0
Can Yoldas On

You can use delegates instead of having hardcoded functions in your CustomView.

class CustomView: UIView {
  weak var delegate: CustomViewDelegate?
 @objc  func nextButtonpressed() {
  delegate?.pushDetailView()
}

class ViewController: UIViewController, CustomViewDelegate {

   let customView: CustomView {
      let view = CustomView()
      view.delegate = self
      return view
   }

   func pushDetailView() {
    let detailVC = ViewController()
    self.navigationController.pushViewController(detailVC, animated: true)
   }
}

Don't forget to check if you have navigation controller on your stack tho.