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?
This extension may help you -- it computes and sets the corner radius for a given UIView
instance based on its frame
property:
extension UIView {
/**
Magically computes and sets an ideal corner radius.
*/
public func magicallySetCornerRadius() {
layer.cornerRadius = 0.188 * min(frame.width, frame.height)
layer.masksToBounds = true
}
}
Here's how I've used it in a "ViewController.swift" file for three differently sized UIButtons
:
import UIKit
class ViewController: UIViewController {
private func addButton(frame: CGRect, backgroundColor: UIColor) {
let button = UIButton(frame: frame)
button.backgroundColor = backgroundColor
button.magicallySetCornerRadius()
button.layer.borderColor = UIColor.black.cgColor
button.layer.borderWidth = 1.0
view.addSubview(button)
}
override func viewDidLoad() {
super.viewDidLoad()
addButton(frame: CGRect(x: 40.0, y: 100.0, width: 100.0, height: 300.0), backgroundColor: .blue)
addButton(frame: CGRect(x: 160.0, y: 180.0, width: 100.0, height: 100.0), backgroundColor: .green)
addButton(frame: CGRect(x: 160.0, y: 300.0, width: 180.0, height: 100.0), backgroundColor: .red)
addButton(frame: CGRect(x: 40.0, y: 420.0, width: 300.0, height: 150.0), backgroundColor: .yellow)
}
}
... and this is what the result looks like:
Try this code:
btn1
, btn2
and btnarrival
are UIButton
instances:
btn1.setCornerRadius()
btn2.setCornerRadius()
btnarrival.setCornerRadius()
extension UIButton {
func setCornerRadius() {
layer.cornerRadius = frame.size.height / 2.0
clipsToBounds = true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With