如何从自定义UICollectionViewCell NIB呈现popoverPresentationController

时间:2017-10-16 15:02:46

标签: ios swift uicollectionviewcell nib uipopoverpresentationcontroller

我有一个在UIViewController中定义的弹出框,但现在需要从自定义UICollectionViewCell中显示。 present不再起作用,因为类是UICollectionViewCell而不再是UIViewController。如何从自定义UICollectionViewCell中显示弹出窗口。

   @IBAction func period(_ sender: Any) {

        let storyboard = UIStoryboard(name: "ScoreClockPopoverViewController", bundle: nil)
        let scoreClockPopoverViewController = storyboard.instantiateViewController(withIdentifier: "ScoreClockPopoverViewController") as! ScoreClockPopoverViewController

        scoreClockPopoverViewController.modalPresentationStyle = .popover

        let popover = scoreClockPopoverViewController.popoverPresentationController!
        popover.delegate = self
        popover.permittedArrowDirections = .any
        popover.sourceView = periodButton
        popover.sourceRect = periodButton.bounds


        present(scoreClockPopoverViewController, animated: true, completion:nil)
       //Error: Use of unresolved identifier 'present'

    }

如果我尝试将UICollectionViewCell扩展为UIViewContoller,我会收到以下错误:Extension of type 'HeaderCollectionViewCell' cannot inherit from class 'UIViewController'

1 个答案:

答案 0 :(得分:0)

CollectionViewcontroller设为CollectionViewCell的代表。

调用CollectionViewCell上的句点函数时,调用" didClickPeriod"单元格委托的功能(您自己创建)。

包含此内容,例如在你的牢房里

protocol HeaderCollectionViewCellDelegate {
    func didClickPeriod(sender: Any)
}

确保单元格具有属性

var delegate: HeaderCollectionViewCellDelegate!

注意!假设您从Storyboard实例化,您无法在实例化时传递您的委托,但必须手动填写#34;手动"。的!基本上声明你可以使用这个属性,就好像它总是被设置 - 假设你正确地填充属性,这将节省你一直打开。如果你不这样做,你将会崩溃。

在你的期间功能中,只需

@IBAction func period(_ sender: Any) {
   self.delegate.didClickPeriod(sender)
}

CollectionViewController中确保它实施协议,例如包括

extension YourCollectionViewController: HeaderCollectionViewCellDelegate {
    func didClickPeriod(sender: Any) {
        // your previous presentation logic. 
        // But now you're in the CollectionViewController so you can do
       ...
       present(scoreClockPopoverViewController, animated: true, completion:nil)

    }
}