Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // AspectFitAutoLayoutImageView.swift
- //
- // Created by Tanguy Gourvez on 28/06/2016.
- // Copyright © 2016 10sApps. All rights reserved.
- //
- import UIKit
- class AspectFitAutoLayoutImageView: UIImageView {
- var aspectFitRatioConstraint: NSLayoutConstraint?
- override var image: UIImage? {
- didSet {
- updateImageConstraintsIfNeeded()
- }
- }
- override func awakeFromNib() {
- updateImageConstraintsIfNeeded()
- }
- // MARK: - Constraints
- func updateImageConstraintsIfNeeded() {
- if self.contentMode == .ScaleAspectFit {
- setNeedsUpdateConstraints()
- updateFocusIfNeeded()
- }
- }
- override func updateConstraints() {
- if let aspectFitRatioConstraint = aspectFitRatioConstraint {
- removeConstraint(aspectFitRatioConstraint)
- }
- if let image = image {
- let aspectRatio = image.size.height / image.size.width
- if !isnan(aspectRatio) {
- aspectFitRatioConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: aspectRatio, constant: 0)
- aspectFitRatioConstraint?.priority = UILayoutPriorityRequired
- addConstraint(aspectFitRatioConstraint!)
- setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal)
- setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Vertical)
- }
- }
- super.updateConstraints()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement