首页 > 解决方案 > 如何将 UIAlertController 操作表锚定到特定单元格 UICollectionView?

问题描述

在尝试将警报锚定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)
}

标签: swift

解决方案


您的代码的问题是您正在使可重复使用的单元格出列,而不是让单元格处于适当位置。dequeueReusableCell如果没有准备好缓存副本,将创建一个新单元格。在您的情况下,这是创建一个单元格,size zero因此frame 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)
}

这是我的样本的输出

在此处输入图像描述


推荐阅读