将 UIViewController 中的 UIView 显示为上下文菜单预览

Show UIView from UIViewController as a context menu preview

我正在试验 iOS 13 和新的 UIContextMenu API,当尝试使用上下文菜单预览时,我想显示一张与按下的 UITableRow 相关的小卡片。我在故事板中创建了一个 UIViewController,其中包含一个包含信息卡本身的 UIView(我制作了 UIView,以便我可以轻松地通过约束更改其大小)。我尝试只通过

来显示它
@IBOutlet var infoCard = UIView!
override func loadView(){
    super.loadView()
    view = infoCard
    preferredContentSize = infoCard.bounds.size
}

但是,当显示上下文菜单时,我看到了视图,但卡片上方和下方有黑色矩形,因为预览的比例没有改变。

如何以其他比例显示此信息卡片?谢谢!

我终于成功了,我遇到的问题是 infoCard.bounds 会 return 故事板值,但我的视图具有动态大小,而 Swift 不会t 尝试重新计算可见的 height/width 直到框架被绘制。下面是当 UIViewController 显示在上下文菜单预览中时,用于在 UIViewController 中呈现 UIView 的代码:

// All this is inside the view controller, with cardView being the displayed view
loadViewIfNeeded()
updateViewConstraints()

// This will force Swift to recalculate the view's size
cardView.drawHierarchy(in: cardView.bounds, afterScreenUpdates: true)

view = cardView
preferredContentSize = cardView.bounds.size