You are adding the code in the wrong place, drawRect: is not really the right method to do such a functionality for editing the layer, you can achive this by:
Editing the layer when init(frame:) the imageView (also, adding the same functionality in init(coder:) because it should work for both approaches: programmatically and via storyboard):
class CircleImageView: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
setupCircleLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupCircleLayer()
}
private func setupCircleLayer() {
layer.masksToBounds = true
layer.cornerRadius = min(frame.width/2 , frame.height/2)
clipsToBounds = true
}
}
Or as @Mohammadalijf suggested in his answer by overriding layoutSubviews() method:
class CircleImageView: UIImageView {
override func layoutSubviews() {
super.layoutSubviews()
layer.masksToBounds = true
layer.cornerRadius = min(frame.width/2 , frame.height/2)
clipsToBounds = true
backgroundColor = UIColor.black
}
}
It does the desired fucntionality that you are asking for, but note that:
Subclasses can override this method as needed to perform more precise
layout of their subviews. You should override this method only if the
autoresizing and constraint-based behaviors of the subviews do not
offer the behavior you want. You can use your implementation to set
the frame rectangles of your subviews directly.
i.e, it is related to updating the layout of the view, check the documentation for more information; That's why I prefer to do it in the init
methods.