0

I want to override the ContentMode of the UIImageView so I wrote this code but it doesn't seem to work as expected.

class AspectFitUIImageView: UIImageView {

    override var contentMode: UIViewContentMode {
        get {
            return .scaleAspectFit
        }

        set {
            // contentMode = contentMode
        }
    }
}

Can any one tell me where I am wrong?

Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56
Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57

1 Answers1

0

You should set the contentMode in awakeFromNib() like so:

class AspectFitUIImageView: UIImageView {

    override func awakeFromNib() {
       super.awakeFromNib()
       contentMode = .scaleAspectFit
    }

}

Or if you are not planning on using a Nib or Storyboard, you can use the following:

override init(frame: CGRect) {
    super.init(frame: frame)
    contentMode = .scaleAspectFit
}
Zach Fuller
  • 1,219
  • 2
  • 14
  • 18