【问题标题】:How to anchor UIAlertController action sheet to specific cell UICollectionView?如何将 UIAlertController 操作表锚定到特定单元格 UICollectionView?
【发布时间】:2019-12-31 05:55:14
【问题描述】:

在尝试将警报的 popoverPresentationController 锚定到特定的 UICollectionViewCell 时,我发现它只会锚定到 UINavigationController

为了以编程方式触发此警报控制器并将其锚定到用户选择的单元格,我需要采取哪些步骤?

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let selectedCell = collectionView.dequeueReusableCell(withReuseIdentifier: PersonCell.reuseIdentifier, for: indexPath)
    let person = people[indexPath.item]

    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { ... }))
    alert.addAction(UIAlertAction(title: "Rename", style: .default, handler: { ... }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))

    alert.modalPresentationStyle = .popover
    alert.popoverPresentationController?.sourceView = selectedCell
    alert.popoverPresentationController?.sourceRect = CGRect(x: selectedCell.bounds.maxX, y: selectedCell.bounds.midY, width: 0, height: 0)
    present(alert, animated: true)
}

【问题讨论】:

  • 添加您用来显示警报控制器的代码。
  • @PGDev 添加了我目前正在使用的代码,这似乎与文档一致
  • @Cerlin 是的,但感谢您的链接;我还没有看到那个线程,但它基本上说了我尝试过的同样的事情。我还尝试安全地打开属性并设置在里面。
  • 如我提供的链接中所述,如果模态表示样式不是popoveralert.popoverPresentationController 将为 nil。在访问popoverPresentationController之前,先执行alert.modalPresentationStyle = .popover

标签: swift


【解决方案1】:

您的代码的问题在于,您将一个可重复使用的单元格出列,而不是让单元格位于位置。dequeueReusableCell 如果没有准备好缓存副本,将创建一个新单元格。在您的情况下,这是使用 size zeroframe zero (x = 0, y = 0) 创建一个单元格,因此指针指向该单元格。

你应该改用collectionView.cellForItem(at: indexPath)

所以你的最终代码看起来类似于下面的代码

if let selectedCell = collectionView.cellForItem(at: indexPath) {
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { ... }))
    alert.addAction(UIAlertAction(title: "Rename", style: .default, handler: { ... }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))

    alert.modalPresentationStyle = .popover
    alert.popoverPresentationController?.sourceView = selectedCell
    alert.popoverPresentationController?.sourceRect = CGRect(x: selectedCell.bounds.midX, y: selectedCell.bounds.maxY, width: 0, height: 0)
    present(alert, animated: true)
}

这是我的样本的输出

【讨论】:

  • 天啊!那是票。谢谢@Cerlin!
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 2016-02-28
  • 1970-01-01
相关资源
最近更新 更多