由于内容模式缩小图像时,使图像视图调整其高度以匹配其图像的高度

时间:2016-02-10 10:41:27

标签: ios uiimageview autolayout interface-builder aspect-fit

我有一个图像视图,其约束方式使其左,右和上边缘固定到其超视图,其底边与下面的标签有固定的间距。它没有任何宽度或高度限制,因此它应该从图像的内在大小中获得高度。内容模式设置为Aspect Fit

如果图像的宽度小于或等于图像视图,则效果很好(案例1和2,见下图)。但是,如果图像的宽度超过其包含图像视图的宽度,则会遇到问题(案例3):

图像按预期缩小,使其宽度与图像视图的宽度相匹配。 但是图片视图并未相应地更新其高度,在上方和下方留下空白区域。我知道图片视图仍然可以从图像的原始高度获得高度。但由于内容模式,图像的高度现在要小得多,我希望图像视图调整其高度以匹配图像的实际高度。

我正在寻找一个适用于三种情况中的每种情况的简洁解决方案,最好也适用于IB_DESIGNABLE次观看。有什么想法吗?

<案例1

固有宽度&lt;框架宽度

intrinsic width < frame width

<案例2

内在宽度=框架宽度

intrinsic width = frame width

<案例3

内在宽度&gt;框架宽度

intrinsic width > frame width

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式在UIImageView上创建扩展程序:

extension UIImageView {
    @IBInspectable var shouldAdjustHeight: Bool {
        get {
            return self.frame.size.height == self.adjustedHeight;
        }
        set {
            if newValue {
                if !shouldAdjustHeight {
                    let newHeight = self.adjustedHeight

                    // add constraint to adjust height
                    self.addConstraint(NSLayoutConstraint(
                        item:self, attribute:NSLayoutAttribute.Height,
                    relatedBy:NSLayoutRelation.Equal,
                    toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute,
                    multiplier:0, constant:newHeight))
            }
        }
        else {
            let newHeight = self.adjustedHeight
            // create predicate to find the height constraint that we added
            let predicate = NSPredicate(format: "%K == %d && %K == %f", "firstAttribute", NSLayoutAttribute.Height.rawValue, "constant", newHeight)
            // remove constraint
            self.removeConstraints(self.constraints.filter{ predicate.evaluateWithObject($0) })
        }
    }
}

var adjustedHeight: CGFloat {
    let screenWidth = UIScreen.mainScreen().bounds.width
    let deviceScaleFactor = screenWidth/self.bounds.size.width
    return CGFloat(ceilf(Float(deviceScaleFactor * AVMakeRectWithAspectRatioInsideRect((self.image?.size)!, self.bounds).size.height))) // deviceScaleFactor multiplied with the image size for the frame
    // I am using size class in my XIB with value as (Any,Any) and I was not getting correct frame values for a particular device so I have used deviceScaleFactor.
    // You can modify above code to calculate newHeight as per your requirement
}
}

添加上述扩展名后,您可以在Interface-builder中设置属性,如下所示。

enter image description here

在设置此属性时,高度约束将添加到imageView 我的解决方案中adjustedHeight的计算可能不是很整齐,因此您可以进一步调查。

相关问题