代码之家  ›  专栏  ›  技术社区  ›  UK4

Swift-UIAlert在UICollectionViewCell中不工作

  •  0
  • UK4  · 技术社区  · 7 年前

    我在没有故事板的情况下编写代码,现在我遇到了这个问题,因为我找不到好的解决方案。

    所以我想打电话 UIAlert 从…起 UICollectionViewCell 如下所示。

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

    这是我在stackoverflow中发现的,它很有效。

    但当 ViewController 其中有 UICollectionViewCell 从另一方呈现 视图控制器 通过 present(_:animated:completion:) 如下图所示, UIAlert 没有接到电话。

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

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

    3 回复  |  直到 7 年前
        1
  •  2
  •   Abhishek Thapliyal    7 年前

    不,这行不通。如果您想在点击单元格操作时显示警报,则需要为此实现委托

     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")
       }
    }
    

    在viewController中

    该系列的 cellforRow

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

    符合委托状

       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)
    
        }
     }
    
        2
  •  1
  •   Glaphi    7 年前

    您的单元负责显示警报控制器这一事实并不是一个好的设计 cell 应将此授权。如上所述,可以获得视图控制器 单间牢房 位于并显示使用它的警报控制器:

    extension UIView {
        var parentController: UIViewController? {
            var parentResponder: UIResponder? = self
            while parentResponder != nil {
                parentResponder = parentResponder!.next
                if let viewController = parentResponder as? UIViewController {
                    return viewController
                }
            }
            return nil
        }
    }
    

    在您想从单元格中显示控制器的位置:

    if let vc = cell.parentController {
        vc.present(// alert controller)
    }
    
        3
  •  0
  •   Hunaid Hassan    7 年前

    只能从最顶部的视图控制器显示。我假设您正试图从 rootViewController 。如果另一个 viewController 已经呈现在上面了。你的情况是 HomeController

    将其呈现在 家庭控制器 使用 self.present() 呼叫不超过 rootViewController