Skip to content

Instantly share code, notes, and snippets.

@devahmedshendy
Created September 29, 2021 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devahmedshendy/28669caeab812fc5571cc4c82a483a71 to your computer and use it in GitHub Desktop.
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
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)
}
}
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])
}
}
}
@devahmedshendy
Copy link
Author

Screen Shot 2021-09-29 at 8 02 14 PM

Screen Shot 2021-09-29 at 8 00 37 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment