user1282637
user1282637

Reputation: 1867

Perfect round corners on rectangular view

I have a rectangular view that I want "perfectly" round borders on the ends. I'm rounding the corners like so:

    contentView.layer.cornerRadius = 30; //arbitrary number

    contentView.layer.borderWidth = 1.0
    contentView.layer.borderColor = UIColor.white.cgColor

And this is my result:

enter image description here

And this is the result I'm aiming for: enter image description here

I'd like to determine the cornerRadius for my view to achieve rounded ends dynamically. Any ideas? Thanks!

Upvotes: 1

Views: 740

Answers (2)

Xavier L.
Xavier L.

Reputation: 747

If your "contentView" is a class that inherits from a UIView then:

class CustomView: UIView
{
    ...
    override func layoutSubviews()
    {
        super.layoutSubviews() //Don't want to change the default behavior of this func. Just want to add to it.
        layer.cornerRadius = bounds.height / 2
    }
    ...
}

If it's just a plain UIView in a UIViewController, then you can update it in the UIViewController's viewWillAppear(_ animated: Bool) method.

Upvotes: 3

Artem Kirillov
Artem Kirillov

Reputation: 1398

You’re on the right way. Somewhat conventional approach to do it looks like this:

contentView.layer.cornerRadius = contentView.bounds.height / 2

Upvotes: 3

Related Questions