2017-08-29 172 views
1

当我点击一个单元我想推这个视图控制器。如何从UIView推视图控制器

这里是我的代码:

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

    let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout()) 

} 

我想推userProfileController

注:这是一个UIView不是一个视图控制器

+0

你可以从该视图和推视图控制器。 https://stackoverflow.com/a/24590678/6642629 – koropok

+0

你不能从视图推动。 – Pushpendra

+0

考虑为拥有视图的视图控制器创建回调/委托,并从该位置推入下一个视图控制器。 – user3581248

回答

3

不能从UIView的推动任何控制器。要做到这一点,你必须使用NavigationController。

我假设你有你的UIView里面的一些UIViewController,所以许多选项之一将创建一个委托,它会告诉你的视图控制器做推。

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

} 
0

如果在导航控制器堆栈和视图控制器视图控制器所拥有的视图,那么你可以按照 滑块机构从VC

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

分配完成块。

self.navigationController?.pushViewController(userProfileController, animated: true) 
1

试试这个

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

这工作!简单 –

+0

虽然有效,但它很脆弱。最好为您的视图提供owningNavigationController属性,并在视图加载时进行设置。 (您需要在拥有的视图控制器中添加支持代码。) –