How to give Rounded corners to Top or Bottom for Views or Buttons
Posted By : Aditya Kumar Sharma | 14-May-2018
We all know that if we want to create a round-cornered view. We just need to add just these two lines and it's done.
self.view.cornerRadius = 10.0
self.view.clipToBounds = true
Apple has made it very easy for us to create rounded corners views. But what if we just want top or Bottom corners to be rounded only. Let’s make this.
Just open a new Playground and add following lines:
import UIKit
import PlaygroundSupport
class RoundedCornersController : UIViewController {
var templateView: UIView!
override func loadView() {
let view = UIView()
view.backgroundColor = .black
templateView = UIView()
view.addSubview(templateView)
templateView.translatesAutoresizingMaskIntoConstraints = false
templateView.widthAnchor.constraint(equalToConstant: 250).isActive = true
templateView.heightAnchor.constraint(equalToConstant: 250).isActive = true
templateView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
templateView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
templateView.backgroundColor = UIColor.yellow
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
templateView.roundCorner( 10)
}
}
extension UIView {
func roundCorner(_ cornerRadius: Double) {
self.layer.cornerRadius = CGFloat(cornerRadius)
self.clipsToBounds = true
}
}
// This will present the controller in the Live View window
PlaygroundPage.current.liveView = RoundedCornersController()
In iOS 11, we got a new property “maskedCorners”. This is related to CACornerMask which has possible 4 values:
- layerMinXMaxYCorner - Bottom left corner
- layerMinXMinYCorner - Top left corner
- layerMaxXMaxYCorner - Bottom right corner
- layerMaxXMinYCorner - Top right corner
By default, all corners are set to be displayed. But now if we want to set corner radius to just bottom. Then just add following in the viewDidLoad().
self.templateView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
And as a result, we will get this.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Aditya Kumar Sharma
Aditya is a bright iOS developer, have knowledge of objective C, swift, swift 3, JSON, Core data and iPhone development. Apart from that he loves to travel and explore new things.