Swift
iOS
UIView
cornerRadius
programming tips

How to set cornerRadius for only top-left and top-right corner of a UIView?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Setting the cornerRadius for only the top-left and top-right corners of a UIView in iOS development can significantly enhance the user interface design with rounded appearances. Unlike a simple cornerRadius applied to all corners, specifying corners requires use of additional techniques. Here's a comprehensive guide on how to achieve this selectively in Swift.

Understanding UIView and Its Layer Property

Every UIView in iOS has an associated CALayer. This layer allows for more granular control over visual properties, including applying rounded corners, borders, shadows, and more.

The cornerRadius Property

The cornerRadius property on a UIView's layer provides a way to round all the corners of the view. However, when you want to apply this only to specific corners, you'll need to combine cornerRadius with maskedCorners, introduced in iOS 11.

Applying cornerRadius to Specific Corners

Here is how you can apply a cornerRadius to only the top-left and top-right corners of a UIView.

Step-by-Step Guide

1. Import Necessary Modules

First, ensure you have the necessary imports in your Swift file:

swift
import UIKit

2. Configure the UIView

When configuring your view, you'll want to access and modify its layer property directly. Below is an example of how this can be done:

swift
1class CustomView: UIView {
2
3    override init(frame: CGRect) {
4        super.init(frame: frame)
5        setupView()
6    }
7    
8    required init?(coder: NSCoder) {
9        super.init(coder: coder)
10        setupView()
11    }
12    
13    private func setupView() {
14        // Set the desired corner radius
15        let cornerRadius: CGFloat = 20.0
16        
17        // Set corner radius
18        self.layer.cornerRadius = cornerRadius
19        
20        // Enable masking of specified corners
21        self.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
22        
23        // Ensure rendering with a mask
24        self.layer.masksToBounds = true
25    }
26}

Explanation:

  • layer.cornerRadius: Specifies how rounded the corners should be.
  • layer.maskedCorners: Takes an array of corners to apply the radius to. CALayer provides constants for each corner (.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner).
  • layer.masksToBounds: Ensures that the subviews and the layer itself are clipped to the bounds of the view including corner radius.

Compatibility

This approach requires a minimum deployment target of iOS 11. For iOS versions prior to 11, you would need a more complex approach involving UIBezierPath and CAShapeLayer.

Advanced Considerations

Using UIBezierPath for Precise Customization

For increased customization or compatibility concerns when dealing with layers and path-based manipulation, UIBezierPath combined with CAShapeLayer can offer a powerful alternative.

Example:

swift
1private func applyRoundCorners(view: UIView, corners: UIRectCorner, radius: CGFloat) {
2    let path = UIBezierPath(roundedRect: view.bounds, 
3                            byRoundingCorners: corners, 
4                            cornerRadii: CGSize(width: radius, height: radius))
5    let mask = CAShapeLayer()
6    mask.path = path.cgPath
7    view.layer.mask = mask
8}

Usage:

swift
1override func layoutSubviews() {
2    super.layoutSubviews()
3    applyRoundCorners(view: self, corners: [.topLeft, .topRight], radius: 20)
4}

Key Considerations

  • Apply the mask in layoutSubviews, as the view's bounds are fully calculated and correct at this point.
  • Any dynamic resizing may require updating the mask if view dimensions change.

Summary Table

ConceptDescriptioniOS Version
layer.cornerRadiusRounds all corners of the view's layeriOS 2.0 and later
layer.maskedCornersCustomizes which corners to roundiOS 11.0 and later
layer.masksToBoundsEnsures content and subviews are clippediOS 2.0 and later
UIBezierPath & CAShapeLayerAdvanced customizability of corner roundingAll iOS versions with Core Graphics

This approach to customizing corner radii allows developers to bring subtle yet impactful enhancements to app design, ensuring a consistent and pleasing UI/UX experience across devices and orientations.


Course illustration
Course illustration

All Rights Reserved.