2017-05-05 95 views
0

我正在使用外部委托文件来处理所有的UICollectionView的处理,我努力让集合视图单元格通过委托文件执行基于选定单元格的segue。Swift UICollectionView委托执行segue

这就是我目前拥有的委托文件中:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let cell = collectionView.cellForItem(at: indexPath) 
    let mainController = MainController() 
    mainController.performSegue(withIdentifier: "detailSegue", sender: cell) 


} 

,并在主控制器我有:

override func performSegue(withIdentifier identifier: String, sender: Any?) { 
    if identifier == "detailSegue" { 
     let detailController = DetailController() 
     self.present(detailController, animated: true) 
    } 
} 

我得到的错误:

Warning: Attempt to present <DetailController: 0x7fbed8e6e4b0> on <MainController: 0x7fbedda79830> whose view is not in the window hierarchy! 

我想我可以通过委托调用参考,它会呈现控制器。

感谢

回答

1

MainController你参考下面试图得到像是错误的。

let mainController = MainController() 

这不会给你的对象,而不是这一点,将创建MainController的新对象给你这不是在预览层次的加载/预览实例。所以你需要一个实际的预览实例。

解决方案 在您委托类创建的UIViewController类型的一个全局对象,并通过你预览类的引用,这样,当你需要你可以使用它。

例子。

class DelegateDataSource: NSObject { 
    var viewController: UIViewController? 
    //Other Methods/Objects that you need. 
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let cell = collectionView.cellForItem(at: indexPath) 
    if let mainController = viewController as? MainController { 
     mainController.performSegue(withIdentifier: "detailSegue", sender: cell) 
    } 



} 
} 

class MainController: UIViewController { 

    var delegateDataSource: DelegateDataSource? 
    func initializeDelegates() { 
     //Initialize you datasource object and do some tasks that you need and then assign your current instance to this class like this. 
     delegateDataSource.viewController = self 
    } 

} 
+0

工作,非常感谢。 – user7684436

+0

委托人应该弱,不要导致保留周期....'弱var viewController:UIViewController?'也最好通过使用协议解耦代码 – Luzo

0
let mainController = MainController() 
mainController.performSegue(withIdentifier: "detailSegue", sender: cell) 

这是行不通的,无论是使用委托模式,或使用Singleton模式,为您MainController。

-1

只有已经存在的控制器才能显示另一个控制器。该班是否实施didSelectItemAt a UIViewController?如果是这样,为什么不只是这样做:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
    let cell = collectionView.cellForItem(at: indexPath) 
    performSegue(withIdentifier: "detailSegue", sender: cell) 
}