swift - 如何将 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)
}
解决方案
您的代码的问题是您正在使可重复使用的单元格出列,而不是让单元格处于适当位置。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)
}
这是我的样本的输出
推荐阅读
- python - 致命错误:Python.h 没有这样的文件或目录 - 但已经安装了 python-dev
- c# - 触发自动生成的 DataGrid 列
- javascript - Laravel - Uncaught ReferenceError: jQuery is not defined - at jquery.steps.min.js:6
- post - 富媒体共享 - 无法解析表单内容 Linkedin API v2
- c++ - 将文件从一个目录移动到另一个目录
- sql - 显示剩余数据组中小于特定日期但最大值的最大日期
- javascript - 仅将用户名存储在 cookie 中是不好的做法
- python - 合并两个大数据框导致内存错误
- awk - 如何打印最后一列最大值的对应行?
- php - 如果字段为空,则在限制参数中设置 fetch all 选项