Advertisement
Guest User

Untitled

a guest
Jun 28th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. //
  2. // AspectFitAutoLayoutImageView.swift
  3. //
  4. // Created by Tanguy Gourvez on 28/06/2016.
  5. // Copyright © 2016 10sApps. All rights reserved.
  6. //
  7.  
  8. import UIKit
  9.  
  10. class AspectFitAutoLayoutImageView: UIImageView {
  11.  
  12. var aspectFitRatioConstraint: NSLayoutConstraint?
  13.  
  14. override var image: UIImage? {
  15. didSet {
  16. updateImageConstraintsIfNeeded()
  17. }
  18. }
  19.  
  20.  
  21. override func awakeFromNib() {
  22. updateImageConstraintsIfNeeded()
  23. }
  24.  
  25. // MARK: - Constraints
  26.  
  27. func updateImageConstraintsIfNeeded() {
  28. if self.contentMode == .ScaleAspectFit {
  29. setNeedsUpdateConstraints()
  30. updateFocusIfNeeded()
  31. }
  32. }
  33.  
  34. override func updateConstraints() {
  35. if let aspectFitRatioConstraint = aspectFitRatioConstraint {
  36. removeConstraint(aspectFitRatioConstraint)
  37. }
  38.  
  39. if let image = image {
  40. let aspectRatio = image.size.height / image.size.width
  41. if !isnan(aspectRatio) {
  42. aspectFitRatioConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: aspectRatio, constant: 0)
  43. aspectFitRatioConstraint?.priority = UILayoutPriorityRequired
  44. addConstraint(aspectFitRatioConstraint!)
  45.  
  46. setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal)
  47. setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Vertical)
  48. }
  49. }
  50. super.updateConstraints()
  51. }
  52.  
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement