Keywords: SwiftUI | corner rounding | UI customization
Abstract: This article discusses methods to round only specific corners of a view in SwiftUI, including built-in solutions for iOS 16+ and compatible approaches for iOS 13+. Detailed code examples and explanations are provided to aid developers in flexible UI customization.
Introduction
In SwiftUI development, rounding corners of views is a common UI customization need. The standard method .cornerRadius() rounds all corners, but sometimes only specific corners, such as top or bottom, need to be rounded. This article presents two implementation methods covering compatibility across different iOS versions.
iOS 16+ Built-in Method
Starting from iOS 16, SwiftUI introduces the UnevenRoundedRectangle shape, allowing direct specification of each corner's radius using the .clipShape() modifier. For example, the following code rounds the top-left and bottom-right corners:
.clipShape(
.rect(
topLeadingRadius: 0,
bottomLeadingRadius: 20,
bottomTrailingRadius: 0,
topTrailingRadius: 20
)
)Note: This method requires Xcode 15 or later to ensure the availability of the .rect modifier.
iOS 13+ Compatible Method
For older iOS versions, specific corner rounding can be achieved by extending View and customizing a Shape. First, define a RoundedCorner struct as a shape:
struct RoundedCorner: Shape {
var radius: CGFloat = .infinity
var corners: UIRectCorner = .allCorners
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}Then, extend View to add a custom modifier:
extension View {
func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape( RoundedCorner(radius: radius, corners: corners) )
}
}Usage example: .cornerRadius(20, corners: [.topLeft, .bottomRight]) rounds the top-left and bottom-right corners.
Comparison and Selection
The iOS 16+ method is more concise, leveraging built-in APIs, but requires newer development environments. The iOS 13+ method offers broader compatibility, suitable for apps needing support for older iOS versions. Developers should choose based on target user base and device versions.
Conclusion
Through the methods described in this article, developers can flexibly implement specific corner rounding in SwiftUI, enhancing UI customization and user experience. It is recommended to use the iOS 16+ built-in method for code simplicity or opt for the custom extension when compatibility is a priority.