Overriding the class's property swift

180 views Asked by At

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?

1

There are 1 answers

1
Zach Fuller On

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
}