我有一个包含两张图片的 UITableViewCell
,我的目标是在用户长按时展开这些图片。在最好的情况下,图像会覆盖整个屏幕,并带有一个小的“x”或其他要关闭的东西。
我在自定义 UITableViewCell
中使用了以下函数,但图像仅扩展了单元格的大小。我不知道如何在 super View 的整个 tableview/navBar/tabbar 上扩展图像。
@objc func answerOneLongPress(_ sender: UILongPressGestureRecognizer) {
let imageView = sender.view as! UIImageView
let newImageView = UIImageView(image: imageView.image)
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
newImageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
newImageView.backgroundColor = .black
newImageView.contentMode = .scaleAspectFit
self.addSubview(newImageView)
}
如果您需要更多信息,请告诉我。我觉得这应该发生在 UITableViewController
中而不是单元格中,但无法让它以这种方式工作。
最佳答案
您不应将 View 添加到单元格,而应添加到 View Controller 或关键窗口。这取决于您的需要。在你的情况下发生的是你的 ImageView 被添加到一个单元格上并被剪裁并且它没有正确定位。
我会使用某种对象来处理此图像的呈现。让代码自己说话:
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?()
}
}
}
正如您所说,仍然必须添加一个按钮,然后可以在 View 上调用关闭。
注意:我提供的代码并未经过真正测试,只是快速组合在一起。如果有任何问题,请告诉我,以便我对其进行修改。
关于ios - 展开 UITableViewCell UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51147726/