Tutorial – Rounded Buttons
In this post we will look at how to make curved buttons / uibutton in Swift that look like:
First of all in your XCode project add a button to the storyboard. Once added connect it up to your ViewController (The default for a new project will be ViewController.swift). To this with the storyboard open click the assistant editor button in the upper right corner. Now the view is split drag the button to the view controller code by clicking on it and holding the control button and releasing. Name it btnRounded like the following:
Now that that’s done add the following code in the viewDidLoad() to make the button have a border and make it rounded.
btnRounded.layer.borderColor = UIColor.blue.cgColor // Set border color btnRounded.layer.borderWidth = 1 // Set border width btnRounded.layer.cornerRadius = 5 // Set border radius (Make it curved, increase this for a more rounded button
The comment’s next to the code outline what is happening. Run the app and you will see your rounded button!
Wait a minute – the border colour is slightly different then the button colour??. Yes – the inbuilt blueColour.CGColour is not the same as the button colour. To make it exactly the same we need to use the following RGB in the borderColour:
btnRounded.layer.borderColor = UIColor(red: 81/255, green: 159/255, blue: 243/255, alpha: 1).cgColor
Volla! Now you have a rounded ! You can have a play around with it, such as setting the border colour with the following:
btnRounded.layer.backgroundColor = UIColor.green.cgColor