Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make custom rounded UIImageView subclass?

I want to make my custom round UIImageView and show it in storyboard.

I've done next:

@IBDesignable
class RoundedImageView: UIImageView {
    override init(image: UIImage?) {
        super.init(image: image)
        super.layer.cornerRadius = super.frame.size.height / 2
        self.layer.cornerRadius = self.frame.size.height / 2    
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        super.layer.cornerRadius = super.frame.size.height / 2
        self.layer.cornerRadius = self.frame.size.height / 2
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        super.layer.cornerRadius = super.frame.size.height / 2
        self.layer.cornerRadius = self.frame.size.height / 2
    }
} 

And my imageView in storyboard is RoundedImageView class selected. But in storyboard it's still showing as rectangle. How can I realize it? When I'm running code its rounded. Thanks

like image 230
Vlad Pulichev Avatar asked Apr 19 '17 09:04

Vlad Pulichev


1 Answers

You should set radius after layouts have been applied.

@IBDesignable
class RoundedImageView: UIImageView {
    override init(image: UIImage?) {
        super.init(image: image)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.frame.size.height / 2
        self.clipsToBounds = true
    }
}
like image 162
ankit Avatar answered Nov 02 '22 00:11

ankit