我在没有 Storyboard的情况下进行编码,现在我遇到了这个问题,因为我找不到好的解决方案。
所以我正在尝试从 UICollectionViewCell
调用 UIAlert
,如下所示。
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
这是我在 stackoverflow 中找到的并且有效。
但是当具有 UICollectionViewCell
的 ViewController
由 present(_: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/