简体   繁体   中英

How do I push a view controller from a UIView

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

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)
    } 

}

尝试这个

(superview?.next? as? UIViewController)?.navigationController?.pushViewController("your viewcontroller object", animated: false)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM