我能够以某种方式解决第一个问题。主要思想是使用快照而不是单元格的视图。这样即使 tableView 重新加载,快照也保持不变。
您必须实现这两种方法并在那里提供快照:
tableView(_:previewForHighlightingContextMenuWithConfiguration:)
tableView(_:previewForDismissingContextMenuWithConfiguration:)
在我的代码中,它看起来像这样:
func tableView(_: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
guard
let messageId = configuration.identifier as? String,
let indexPath = dataSource.indexPath(for: messageId),
let cell = tableView.cellForRow(at: indexPath) as? YourCustomCell else {
return nil
}
return makeTargetedPreview(cell: cell)
}
func makeTargetedPreview(cell: YourCustomCell) -> UITargetedPreview? {
guard
let previewView = cell.viewYouWantToDisplay,
let snapshot = previewView.snapshotView(afterScreenUpdates: false)
else {
return nil
}
// 1. Prepare how should the view in the preview look like
let parameters = UIPreviewParameters()
parameters.backgroundColor = .clear
parameters.visiblePath = UIBezierPath(roundedRect: previewView.bounds, cornerRadius: previewView.layer.cornerRadius)
// 2. Prepare UIPreviewTarget so we can use snapshot
let previewTarget = UIPreviewTarget(
container: previewView,
center: CGPoint(x: previewView.bounds.midX, y: previewView.bounds.midY)
)
// 3. Return UITargetedPreview with snapshot
// important ! We can't use cell's previewView directly as it's getting changed when data reload happens
return UITargetedPreview(view: snapshot, parameters: parameters, target: previewTarget)
}
注意:实现previewForDismissing(...)
类似。