Adams Adams - 6 months ago 33
iOS Question

How to create an UIImageView extension that is rounded by itself

I've been experiencing an annoying problem recently.

Assume I want to use an image in multiple places across my application, and everywhere it has to be rounded so as to be a circle.
Because I want my code to be clean, I think that this functionality (of rounding itself) should be put inside the class extending UIImageView.
I have created a simple class that overrides storyboard constructor and is responsible for setting cornerRadius properly:

class RoundedImageView: UIImageView {


required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = self.frame.size.width/2
self.layer.borderColor = UIColor.redColor().CGColor
self.layer.borderWidth = 2
self.layer.masksToBounds = true
}
}


For constraints like


  • width : 100,

  • height : 100

    this obviously works, as the frame is not changed after the constructor is called (because it has correct dimensions in storyboard). The problem occurs when, for example, the constraints look like this:

  • width equals to 0.5 superview's

  • aspect ratio: 1:1



because the frame changes after the constructor is called.

What I ended up doing is something like this:

override func viewDidLayoutSubviews(){
super.viewDidLayoutSubviews()
myRoundedImageInstance.layer.cornerRadius = ...
}


in every view controller that has the instance of this class inside...
...which works, because the frame is recalculated after the imageView changes dimensions but this is ugly, and existence of the class seems to be unnecessary in this case.

I tried putting frame's recalculation in drawRect - doesn't work either.
Any ideas?

Answer

You could move your circle updating code into your layoutSubviews method.