How to create a Rounded corner UIView in iOS with Swift 4

How to create a rounded corner UIView in iOS ( Swift-3 or Swift-4 ) :

Rounded corner UIVIew is useful in many cases like to create a custom button or to create a custom notification etc. In this tutorial, we will learn how to create a rounded corner UIView in XCode. This code is compatible with both Swift-3 and Swift-4 :

Method 1 : Using XCode :

1. In this example, I am adding one simple UIView to a ViewController. Add any height/width to the view and align it to the center of the ViewController as shown below :

 

2. Click on the View and click on the third button of the ‘Utilities’ panel . Now inside ‘User Defined Runtime Attributes’ tab, click on the ‘+’ button and add one new row with ‘Key Path’ as ‘layer.cornerRadius’ , ‘Type’ as ‘Number’ and ‘Value’ as 10 . Value can be any number you want. It is the radius of the corner for each corner of the view.


3. That’s it. Run the application and you will see one cornered view in the middle as below :

Method 2 : Make a view Rounded Programmatically :

We can also achieve the same result programmatically instead of adding attributes in XCode. First connect the UIView to an ‘IBOutlet’ in the Connected ViewController and then add the ‘cornerRadius’ property to that UIView as below :

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var roundView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        roundView.layer.cornerRadius = 10.0
    }

}

The output is same as above .

Leave a Reply