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
、私のソリューションではあまりきちんとしていない可能性があるため、さらに詳しく調べることができます。