Oleg Gordiichuk Oleg Gordiichuk - 1 year ago 114
Swift Question

How properly calculate cornerRadius depending on the button frame

How to calculate

property based on frame of the button to create rounded corners.

I do not like to redefine each time corner
for each button item.

I create extension for the

extension UIButton {

func setRoundedCorners(){
self.layer.cornerRadius = 10
self.layer.borderWidth = 1


And i would like to know how too calculate dynamically
each time i use this function.

The main issue to find function that will calculate .cornerRadius for different button sizes. Example below will show small difference.


Corner radius is 10:

:enter image description here

Corner radius is 15:

enter image description here

Is it possible to find function that will calculate proper value that will give corner radius?

Answer Source

The main idea to get flexible function that will calculate proper corner radius for different buttons based on their frame

I think it's up to you what you pass as the arguments:

extension UIButton {
    func setRoundedCorners(ratio: Double?) {
        if let r = ratio {
            self.layer.cornerRadius = self.frame.size.width*r // for specific corner ratio                            
        } else {

            // circle
            // i would put a condition, as width and height differ:
            if(self.frame.size.width == self.frame.size.height) {
                self.layer.cornerRadius = self.frame.size.width/2 // for circles
            } else {
        self.layer.borderWidth = 1


let button = UIButton()
button.setRoundedCorners(ratio: 0.25) // shape with rounded corners
button.setRoundedCorners() // circle
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download