不应将视图添加到单元格,而应将其添加到视图控制器或关键点窗口。这取决于你的需要。在你的例子中,你的图像视图被添加到一个单元格中,并且被剪裁,而且它的位置也不正确。
我会使用某种对象来处理这个图像的呈现。让代码自己说话:
class ImageOverlayController {
private var startFrame: CGRect
private var backgroundView: UIView
private var imageView: UIImageView
private init(startFrame: CGRect, backgroundView: UIView, imageView: UIImageView) {
self.startFrame = startFrame
self.backgroundView = backgroundView
self.imageView = imageView
}
private convenience init() { self.init(startFrame: .zero, backgroundView: UIView(), imageView: UIImageView()) }
static func showPopupImage(inController viewController: UIViewController? = nil, fromImageView imageView: UIImageView) -> ImageOverlayController {
guard let targetView = viewController?.view ?? UIApplication.shared.keyWindow else { return ImageOverlayController() } // This should never happen
let startFrame = imageView.convert(imageView.bounds, to: targetView)
let backgroundView: UIView = {
let view = UIView(frame: targetView.bounds)
view.backgroundColor = UIColor.black.withAlphaComponent(0.0)
return view
}()
let newImageView: UIImageView = {
let view = UIImageView(frame: startFrame)
view.image = imageView.image
return view
}()
let controller = ImageOverlayController(startFrame: startFrame, backgroundView: backgroundView, imageView: imageView)
backgroundView.addSubview(newImageView)
targetView.addSubview(backgroundView)
UIView.animate(withDuration: 0.3) {
backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
newImageView.frame = targetView.bounds
}
return controller
}
func dimiss(completion: (() -> Void)? = nil) {
UIView.animate(withDuration: 0.3, animations: {
self.imageView.frame = self.startFrame
self.backgroundView.backgroundColor = self.backgroundView.backgroundColor?.withAlphaComponent(0.0)
}) { _ in
self.backgroundView.removeFromSuperview()
completion?()
}
}
}
正如您所说,仍然必须添加一个按钮,然后在视图上调用dispose。
注意:我提供的代码并没有经过真正的测试,只是很快地组合起来。如果有任何问题,请告诉我,以便我修改。