【问题标题】:Swift UICollectionView Delegate perform segueSwift UICollectionView 委托执行 segue
【发布时间】:2017-05-05 10:23:11
【问题描述】:

我正在使用外部委托文件来处理 UICollectionView 的所有处理,并且我正在努力让集合视图单元格通过委托文件根据所选单元格执行转场。

这是我目前在委托文件中的内容:

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!

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

谢谢

【问题讨论】:

    标签: ios swift delegates uicollectionview


    【解决方案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
        }
    
    }
    

    【讨论】:

    • 委托应该很弱,不会导致保留周期....weak var viewController: UIViewController? 最好使用协议解耦代码
    【解决方案2】:
    let mainController = MainController()
    mainController.performSegue(withIdentifier: "detailSegue", sender: cell)
    

    这不起作用,要么使用委托模式,要么对 MainController 使用单例模式。

    【讨论】:

      【解决方案3】:

      只有已经呈现的控制器才能呈现另一个控制器。类是否实现了didSelectItemAt 和UIViewController?如果是这样,为什么不这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        相关资源
        最近更新 更多