Created
September 29, 2021 18:40
-
-
Save devahmedshendy/28669caeab812fc5571cc4c82a483a71 to your computer and use it in GitHub Desktop.
Custom ImageView for Country Flags, Each flag should be rounded maintaining its original width & height ratio. So we make subclass of ImageView to update ration constraint for current image, then subclass it to set rounded feature for the current ImageView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class DetailFlagImageView: RatioConstrainedImageView { | |
//MARK: - Init Methods | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
initView() | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
initView() | |
} | |
override init(image: UIImage?) { | |
super.init(image: image) | |
initView() | |
} | |
private func initView() { | |
self.layer.cornerRadius = CGFloat(15) | |
self.layer.shadowColor = UIColor(named: "background-color")?.cgColor | |
self.layer.shadowOffset = CGSize(width: 2.0, height: 3.0) | |
self.layer.shadowRadius = CGFloat(10) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RatioConstrainedImageView: UIImageView { | |
//MARK: - Properties | |
private var currentRatioConstraint: NSLayoutConstraint? | |
override var image: UIImage? { | |
didSet { | |
updateRatioConstraint() | |
} | |
} | |
//MARK: - Init Methods | |
public override init(frame: CGRect) { | |
super.init(frame: frame) | |
initView() | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
initView() | |
} | |
override init(image: UIImage?) { | |
super.init(image: image) | |
initView() | |
} | |
private func initView() { | |
self.contentMode = .scaleAspectFit | |
self.updateRatioConstraint() | |
} | |
private func updateRatioConstraint() { | |
if let currentConstraint = currentRatioConstraint { | |
self.removeConstraint(currentConstraint) | |
} | |
currentRatioConstraint = nil | |
if let image = image { | |
let aspectRatio = image.size.width / image.size.height | |
let newConstraint = self.widthAnchor.constraint(equalTo: self.heightAnchor, multiplier: aspectRatio) | |
currentRatioConstraint = newConstraint | |
NSLayoutConstraint.activate([newConstraint]) | |
} | |
} | |
} |
Author
devahmedshendy
commented
Sep 29, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment