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 中设置属性,如下所示。
在设置此属性时,高度约束将添加到您的imageView
. 在我的解决方案中,计算adjustedHeight
可能不是很整洁,因此您可以进一步研究。