ios - 将图像大小限制为 ScrollView,Swift

标签 ios swift uiscrollview

我有一个设置在 ScrollView 内的图像,尽管我已经将 ScrollView 的框架设置为固定的高度和宽度,如下所示,但图像超出了范围(见下图)。

如何限制图片以适合 ScrollView 。

imageScrollView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight-50)
imageScrollView.clipsToBounds = true // Has no affect on the image

enter image description here

最佳答案

你有 UIImageView 的引用吗?如果是这样,则将其内容模式设置为纵横比适合。像这样:

        theImageView.contentMode = .scaleAspectFit

您设置的 clipsToBounds 仅覆盖 subview 超出父 View 边界的任何部分,因此它不会为您做任何事情。

或者,如果您使用的是 Interface Builder,请设置此选项: Interface Builder, baby!


那么,如果您没有对 UIImageView 的引用怎么办?... 您可以遍历 ScrollView 的 subview ,只要它找到 UIImageView,您就可以像那样设置内容模式。像这样的东西:

//This is off the top of my head, so my filtering may not be right...
//This is also a one and done solution if you've got a lot of images in your scroll view
for anImgVw in imageScrollView.subviews.filter({$0.isKind(of: UIImageView.self)})
{
    anImgVw.contentMode = .scaleAspectFit
}

否则,我不确定是否可以不引用 UIImageView。

关于ios - 将图像大小限制为 ScrollView,Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674589/

相关文章:

iphone - 如何从表格 View 中删除分隔符?

ios - 共享大块数据 iOS

iphone - 当我将触摸事件传递给 super View 时,MyScrollView 不响应触摸

ios - UIScroll View 额外高度并忽略约束

ios - ScrollView 图片addSubview 问题

iphone - 经销证书

ios - 我可以将 entitlements.plist 添加到越狱调整中吗?

ios - 翻转图像以显示背面的 iOS

ios - 使用 spritekit 无法进行碰撞检测

ios - 【UISearchController/UISearchBar】如何在输入文字时一直显示书签按钮?