3

When I click on a cell I want to push this view controller.

Here's my code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let user = filteredUsers[indexPath.item]
    print(user.username)

    let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())

}

I want to push userProfileController.

Note: This is a UIView not a view controller

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
Erik Batista
  • 227
  • 2
  • 15

3 Answers3

12

You can't push any controller from UIView. To do this you have to use NavigationController.

I'm assuming you have your UIView inside some UIViewController so one of the many options would be to create a delegate that will tell your view controller to do the push.

protocol MyViewDelegate {
    func didTapButton()
}

class MyView: UIView {

    weak var delegate: MyViewDelegate?

    func buttonTapAction() {
        delegate?.didTapButton()
    }
}

class ViewController: UIViewController, MyViewDelegate {

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

    func didTapButton() {
        self.navigationController?.pushViewController(someVc, animated: true)
    } 

}
Michał Kwiecień
  • 2,734
  • 1
  • 20
  • 23
  • 1
    for myView in ViewController, have you just created a new instance of MyView at the beginning of ViewController class? – Iona Ryder Mar 31 '20 at 12:54
  • For creating a custom view for a ViewController, just use the method `loadView`. For more information, take a look here: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621454-loadview – Michał Kwiecień Mar 31 '20 at 16:02
  • 1
    you have not mention how did you get myView where from which makes the answer incomplete – iPhone 7 Jun 11 '20 at 11:13
0

If your view controller in navigation controller stack and View controller holds view then you can follow Block mechanism

func pushViewController(completion: () -> ()) {
}

Assign completion block from VC.

self.navigationController?.pushViewController(userProfileController, animated: true)
PradeepKN
  • 617
  • 7
  • 10
0

Try this

(superview?.next? as? UIViewController)?.navigationController?.pushViewController("your viewcontroller object", animated: false)
karthikeyan
  • 3,821
  • 3
  • 22
  • 45
  • That works, but it's fragile. Better to give your view an owningNavigationController property, and set it up when the view is loaded. (You'll need to add supporting code in the owning view controller.) – Duncan C Aug 29 '17 at 11:21