我使用 UIViewController 作为表格单元格上下文菜单的预览视图。我没有找到一种方法来更改出现在我的视图后面的标准模糊背景的角半径。更改用于预览的视图控制器的角半径不会影响后面的模糊背景,并在每个角上留下这些烦人的边缘:
使用tableView或collectionView的人可以使用所需视图的快照作为上下文菜单的预览。这种方法的主要优点是重新加载底层视图不会影响预览。
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
let item = items[indexPath.row]
let edit = UIAction(title: "Edit",
image: UIImage(systemName: "square.and.pencil")) { (_) in
}
let delete = UIAction(title: "Delete",
image: UIImage(systemName: "trash"), attributes: .destructive) { (_) in
}
let identifier = "\(indexPath.row)" as NSString
return UIContextMenuConfiguration(identifier: identifier, previewProvider: nil, actionProvider: { _ in
return UIMenu(title: "", children: [edit, delete])
})
}
func tableView(_ tableView: UITableView,
previewForHighlightingContextMenuWithConfiguration
configuration: UIContextMenuConfiguration)
-> UITargetedPreview? {
guard let identifier = configuration.identifier as? String,
let index = Int(identifier),
let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0))
else {
return nil
}
return preview(for: cell)
}
func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
guard let identifier = configuration.identifier as? String,
let index = Int(identifier),
let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0))
else {
return nil
}
return preview(for: cell)
}
// generating preview from cell
fileprivate func preview(for cell: UITableViewCell) -> UITargetedPreview? {
// 'mainView' is a subView of my tableview cell of type YourTableViewCell
// you can use any subView as per your requirement.
guard let myCell = cell as? YourTableViewCell,
let snapshot = myCell.mainView.snapshotView(afterScreenUpdates: false) else {
return nil
}
// using mainView's cornerRadius as preview's cornerRadius
let parameters = UIPreviewParameters()
parameters.visiblePath = UIBezierPath(roundedRect: myCell.mainView.bounds,
cornerRadius: myCell.mainView.layer.cornerRadius)
let previewTarget = UIPreviewTarget(container: myCell.mainView,
center: CGPoint(x: myCell.mainView.bounds.midX, y: myCell.mainView.bounds.midY))
return UITargetedPreview(view: snapshot,
parameters: parameters,
target: previewTarget)
}