【问题标题】:How to make a UIImage Scrollable inside a UIScrollView?如何在 UIScrollView 中使 UIImage 可滚动?
【发布时间】:2019-11-16 15:29:54
【问题描述】:

我目前有一个ScrollView,在ScrollView 里面我有一个UIImageView

我从我的服务器获得不同尺寸的图像,并且大多数图像都大于我屏幕的bounds

如果图片比我的屏幕大,我想滚动浏览它。

这样的……

这是我迄今为止尝试过的。

let image = UIImage(named: "myImg")
let heightInPoints = image?.size.height
let heightInPixels = heightInPoints ?? 0 * image!.scale
let widthInPoints = image?.size.width
let widthInPixels = widthInPoints ?? 0 * image!.scale

self.imageView.frame = CGRect(x: 0, y: 0, width: widthInPixels, height: heightInPixels) //= image
self.imageView.image = image

scrollView.contentSize = CGSize(width: imageView.frame.width, height: imageView.frame.height)

但它似乎不起作用。它要么只垂直或水平滚动,要么从不滚动。

我做错了什么。或者有没有更好的方法来获得这种效果?

【问题讨论】:

  • 尝试查看这篇文章Look here 它包含有关您的实施的有用信息
  • @MertalpTasdelen 这不是我想要的。我不想缩放图像....我想计算它的帧大小并使图像视图的大小相同,然后将其添加到滚动视图中,以便我可以向各个方向滚动。

标签: ios swift uiscrollview uiimageview uiimage


【解决方案1】:

解决方案 1. 更新框架

首先,确保视图层次结构设置正确(imageView 被添加到scrollView):

scrollView.addSubview(imageView)

然后我建议将此代码重写为:

let image = UIImage(named: "myImg")
imageView.image = image                        // setup image to imageView
imageView.frame.size = image?.size ?? .zero    // setup image size or zero to imageView
scrollView.contentSize = image.size ?? .zero   // setup image size or zero as a content size

解决方案 2. 使用约束

还有另一个解决方案是使用约束而不是手动设置大小。这需要更多代码,但不需要在更改图像时重新计算尺寸。

scrollView.addSubview(imageView)                            // Setup the views hierarchy
imageView.translatesAutoresizingMaskIntoConstraints = false // Make sure constraints won't interfere with autoresizing mask
NSLayoutConstraint.activate(
    [
        imageView.leftAnchor.constraint(equalTo: scrollView.leftAnchor),    // attaching to the left
        imageView.topAnchor.constraint(equalTo: scrollView.topAnchor),      // attaching to the top
        imageView.rightAnchor.constraint(equalTo: scrollView.rightAnchor),  // attaching to the right
        imageView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor) // attaching to the bottom
    ]
)

然后我们用这样的新图像替换现有图像:

imageView.image = UIImage(named: "myImg") 

这两种方法都适用于 Playground。因此,如果这些仍然不适合您,请分享有关如何设置滚动视图的层次结构和其他参数的更多信息。

【讨论】:

  • 嘿丹尼斯你的Solution 1. Updating Frames 为我工作,所以我会接受这个答案。但最终因为我使用了自动布局,我想出了一种使用自动布局获得相同效果的方法。我还根据图像的高度和宽度缩放图像以完美适应屏幕。因此,通过您的方法,我在扩展方面遇到了一些问题,但对于我提出的问题,这是正确的解决方案。谢谢。
猜你喜欢
  • 2018-12-05
  • 2018-02-04
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2014-10-05
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多