Manuel
Manuel

Reputation: 15042

Corner radius for view after setting text

I have a UIView that contains a UILabel. The size of the UIView adapts to the size of the UILabel.

I want the UIView to be a circle so I set the corner radius:

view.clipToBounds = true
label.text = "123"
view.layer.cornerRadius = view.frame.size.height / 2

However, if I call the code above, the corner radius is not adapted sometimes. It seems as if the UIView frame did not change its size yet. The UIView is inside a UITableViewCell btw.

Upvotes: 1

Views: 1069

Answers (1)

Jeremiah
Jeremiah

Reputation: 1461

If you don't mind subclassing you can do the following:

import UIKit

class RoundedView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = frame.height / 2.0
    }

}

This will adjust the corner radius to the appropriate height anytime the view is resized.

Upvotes: 2

Related Questions