首页 > 解决方案 > 有没有办法捏和缩放以编程方式添加的图像?

问题描述

我试图弄清楚如何将捏合/缩放功能添加到 imageView,但特别是我以编程方式添加到 scrollView 的功能。我能够在 SO 上找到一些很好的示例,以使用带有 viewForZooming 的滚动视图来捏合和缩放图像,但在那种情况下,我必须返回被捏合和缩放的图像视图,如果我以编程方式返回它,这将不起作用。

我的最终目标是拥有一系列图像,用户可以在其中左右滚动以查看所有图像并能够放大它们,基本上就像他们在翻阅照片流一样。我在这里找到了一个可以动态添加图像以进行滚动的教程https://www.codementor.io/taiwoadedotun/ios-swift-implementing-photos-app-image-scrolling-with-scroll-views-bkbcmrgz5#comments-bkbcmrgz5但我不清楚如何添加 viewForZooming,因为图像视图是循环中动态的 .addSubview 。

我创建了一个小示例,其中包含与帖子关联的 0-n 图像的集合视图。一旦点击了带有图像的 collectionViewCell,就会出现一个隐藏的滚动视图,并添加一个新的动态 UIImageView 作为子视图。一切都很好,但我现在不知道如何添加捏/缩放。

@objc func imageTapped(_ sender: UITapGestureRecognizer) {
    print("BlipeFile Image Tapped")
    let imageView = sender.view as! UIImageView
    let newImageView = UIImageView(image: imageView.image)
    //newImageView.frame = UIScreen.main.bounds
    newImageView.contentMode = .scaleAspectFit
    newImageView.clipsToBounds = true
    newImageView.layer.borderColor = UIColor.gray.cgColor
    newImageView.layer.borderWidth = 3.0
    newImageView.frame = self.view.frame
    newImageView.backgroundColor = .black
    newImageView.isUserInteractionEnabled = true
    newImageView.image = imageView.image
    let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
    newImageView.addGestureRecognizer(tap)
    scroller.isHidden = false
    scroller.addSubview(newImageView)
}

@objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
    scroller.isHidden = true
    self.navigationController?.isNavigationBarHidden = false
    self.tabBarController?.tabBar.isHidden = false
    sender.view?.removeFromSuperview()
}


func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return image //Can't return dynamically created newImageView?
}

标签: iosswiftuiscrollviewuiimageview

解决方案


我的最终目标是拥有一组图像,用户可以在其中左右滚动以查看所有图像并能够放大它们

Apple 已经在 WWDC 视频和您可以下载的示例代码中多次解释了这是如何完成的。基本上它只是滚动视图中的滚动视图。外部滚动视图允许水平滚动。内部滚动视图包含一个图像视图并允许缩放。

因此,不要添加图像视图,而是添加包含图像视图的滚动视图。


推荐阅读