Swift - UIAlert 在 UICollectionViewCell 中不起作用

标签 swift uicollectionview

我在没有 Storyboard的情况下进行编码,现在我遇到了这个问题,因为我找不到好的解决方案。

所以我正在尝试从 UICollectionViewCell 调用 UIAlert,如下所示。

self.window?.rootViewController?.present(alert, animated: true, completion: nil)

这是我在 stackoverflow 中找到的并且有效。

但是当具有 UICollectionViewCellViewControllerpresent(_:animated:completion: ) 如下所示,UIAlert 不会被调用。

self.present(HomeController(), animated: true, completion: nil)

有人知道这个问题的解决方案吗?

最佳答案

不,如果你想在来自单元格的点击操作时显示警报,那将不起作用你需要为此实现委托(delegate)

 protocol CollectionViewCellDelegate: class {
    func showAlert(_ cell: CollectionViewCell, _ message: String)
 }

 class CollectionViewCell: UICollectionViewCell {
    ...
    ....
    .....

    weak var delegate: CollectionViewCellDelegate?

   @IBAction func yourButtonAction(_ sender: UIButton) {
       self.delegate?.showAlert(self, "your message")
   }
}

在你的 View Controller 中

集合的cellforRow

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectioView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell

     ....
     cell.delegate = self
     return cell
}

符合像这样的委托(delegate)

   extension YourClass: CollectionViewCellDelegate {

    func showAlert(_ cell: CollectionViewCell, _ message: String) {

       let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .alert)
       alert.addAction(UIAlertAction(title: "title", style: .default, handler: nil)
       self.presentViewController(alert, animated: true, completion: nil)

    }
 }

关于Swift - UIAlert 在 UICollectionViewCell 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49249394/

相关文章:

swift - 无法让 XPC 从客户端接收数据

ios - 小数位值在 swift 中不起作用

ios - 如何修改包含 '-'作为单词字符的单词边界

ios - 如何使用相对于容器调整大小的项目初始化 UICollectionViewController?

ios - .normal 选项在 UIButton 的状态 OptionSet 中不起作用(Swift 3)

ios - 侧边菜单和桌面 View 自定义

ios - 无法让我的标题在 swift 4 中显示在我的 UIcollectionView 页面上

ios - UIPageViewController 中是否可以有多个 UIView

ios - 如何包装自调整大小的 UICollectionViewCell

ios - 如何在 swift 中将 Collection View 转换为圆形 icarousel