How to calculate cornerRadius property based on frame of the button to create rounded corners.
I do not like to redefine each time corner cornerRadius for each button item.
I create extension for the UIButton.
extension UIButton {
func setRoundedCorners(){
self.layer.cornerRadius = 10
self.layer.borderWidth = 1
}
}
And i would like to know how too calculate dynamically cornerRadius 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.
Example:
Corner radius is 10:
Corner radius is 15:
Is it possible to find function that will calculate proper value that will give corner radius?
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
}
}
Usage
let button = UIButton()
button.setRoundedCorners(ratio: 0.25) // shape with rounded corners
button.setRoundedCorners() // circle