[英]iPhone - resizing image and two labels to fit the screen
我是iPhone开发的新手。 我有一个包含图像,标题和内容的屏幕:
图像具有动态大小,并且所有文本都可以具有任何长度。 我要实现的是使图像完全适合屏幕,并使所有标签的长度尽可能长。
经过大约5个小时的工作,我有:
Lines=0
和Preferred Width=content width
来实现的工作标签长度 我已经阅读了很多书,我了解了Content Hugging Priority
和Content Compression Resistance Priority
。 我知道UIViewContentMode
差异。 我知道我可以手动设置UIImage.frame=CGRectMake(...)
什么都没有。 我的图像比更高的宽度更宽(假设width / height = 3)。 如果我有UIViewContentMode=Aspect Fit
则在图像上方和下方将有空白。 如果设置为“ Aspect fill
则图像太高且也被裁剪。 更改代码中的框架不会更改视图中的任何内容。 我想要的是具有使用Aspect fit
制作的图像,但没有空格。
最后我把它弄干净了。 首先,每个人都认为应该修改UIImageView.Frame
来缩小图像,但要注意,如果您的视图是UITableViewCell
则应该在layoutSubviews
方法中执行此操作(请记住在调用时调用super.layoutSubviews()
)。
其次,在IB中为UIImageView
设置一个临时值(例如100)的高度约束。 您将在layoutSubviews
方法中更改该约束。
最后,合适的图像与比例无关。 设置UIViewContentMode=Aspect Fit
。 然后,只有当初始图像比屏幕宽时,才会出现顶部和底部空白的情况。 计算适当的高度也应该在layoutSubviews
。
示例实现:
override func layoutSubviews() {
super.layoutSubviews()
var imageWidth = (imageViewObject.image?.size.width)!
var imageHeight = (imageViewObject.image?.size.height)!
var frameWidth = UIScreen.mainScreen().bounds.width
var properHeight: CGFloat
if imageWidth > frameWidth {
var ratio = frameWidth / imageWidth
properHeight = imageHeight * ratio
}
else {
properHeight = imageHeight
}
imageHeightConstraint.constant = properHeight
imageViewObject.frame = CGRectMake(0, 0, frameWidth, properHeight)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.