presentViewController from TableViewCell

前端 未结 4 1986

I have a TableViewController, TableViewCell and a ViewController. I have a button in the TableViewCell and I want to present ViewController with presentViewController<

4条回答
  •  鱼传尺愫
    2020-12-17 05:56

    I had the same problem and found this code somewhere on stackoverflow, but I can't remember where so it's not my code but i'll present it here.
    This is what I use when I want to display a view controller from anywhere, it gives some notice that keyWindow is disabled but it works fine.

    extension UIApplication
    {
    
        class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController?
        {
            if let nav = base as? UINavigationController
            {
                let top = topViewController(nav.visibleViewController)
                return top
            }
    
            if let tab = base as? UITabBarController
            {
                if let selected = tab.selectedViewController
                {
                    let top = topViewController(selected)
                    return top
                }
            }
    
            if let presented = base?.presentedViewController
            {
                let top = topViewController(presented)
                return top
            }
            return base
        }
    }
    

    And you can use it anywhere, in my case I used:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let vc = storyboard.instantiateViewController(withIdentifier: "WeekViewController")
        UIApplication.topViewController()?.navigationController?.show(vc, sender: nil)
    }
    

提交回复
热议问题