ios – 从UICollectionViewCell呈现AlertView

ios – 从UICollectionViewCell呈现AlertView,第1张

概述我的UICollectionViewCell. swift中有一个按钮:我希望,根据某些参数,它能够呈现警报. class CollectionViewCell: UICollectionViewCell { var collectionView: CollectionView! @IBAction func buttonPressed(sender: UIButton) { 我的UICollectionVIEwCell. swift中有一个按钮:我希望,根据某些参数,它能够呈现警报.

class CollectionVIEwCell: UICollectionVIEwCell {     var collectionVIEw: CollectionVIEw! @IBAction func buttonpressed(sender: UIbutton) {    doThisOrThat()}func doThisOrThat() {    if x == .NotDetermined {        y.doSomething()    } else if x == .DenIEd || x == .Restricted {            showAlert("Error",themessage: "there's an error here")            return        }    }func showAlert(Title: String,themessage: String) {    let alert = UIAlertController(Title: Title,message: themessage,preferredStyle: UIAlertControllerStyle.Alert)    alert.addAction(UIAlertAction(Title: "OK",style: UIAlertActionStyle.Default,handler: nil))    self.collectionVIEw!.presentVIEwController(alert,animated: true,completion: nil)}

在self.collectionVIEw!.presentVIEwController行上我得到了一个休息:

致命错误:在展开Optional值时意外发现nil

我猜这与CollectionVIEw的使用方式有关 – 我还没有完全理解选项.我知道UICollectionCell不能.presentVIEwController – 这就是我试图让UICollectionVIEw去做的原因.

我该如何工作?我曾想过使用扩展但不知道如何让UICollectionVIEwCell采用.presentVIEwController

有任何想法吗?

解决方法 集合视图单元不应依赖于其父视图或视图控制器的知识,以便维护作为适当的应用程序体系结构一部分的职责的功能分离.

因此,为了使小区采用显示警报的行为,可以使用委托模式.这是通过向具有集合视图的视图控制器添加协议来完成的.

@protocol CollectionVIEwCellDelegate: class {        func showAlert()    }

并使视图控制器符合该协议:

class MyVIEwController: UIVIEwController,CollectionVIEwCellDelegate {

还要向单元格添加委托属性:

weak var delegate: CollectionVIEwCellDelegate?

将showAlert()函数移动到集合视图控制器中.

创建单元格时,将单元格的委托指定给集合视图控制器.

func collectionVIEw(collectionVIEw: UICollectionVIEw,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionVIEwCell {    // Other cell code here.    cell.delegate = self

当需要显示警报时,请进行单元格调用

delegate.showAlert()

然后,警报将显示在集合视图控制器上,因为它已被设置为集合视图单元的委托.

总结

以上是内存溢出为你收集整理的ios – 从UICollectionViewCell呈现AlertView全部内容,希望文章能够帮你解决ios – 从UICollectionViewCell呈现AlertView所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1007682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存