SwiftUI: Bring back cornerRadius
In Xcode 15, Apple has marked the cornerRadius
view modifier as deprecated. They suggest to use the clipShape
modifier instead. This change has upset many developers as it makes things more complicated and verbose when all you want is just a simple corner radius on an arbitrary view.
Comparison of cornerRadius and clipShape
Let's take a look at the difference between the two modifiers. We will use a simple Rectangle
view and apply a corner radius of 20 points to it.
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.blue)
.cornerRadius(20)
This will now result in the following warning:
'cornerRadius(_:antialiased:)' will be deprecated in a future version of iOS: Use
clipShape
orfill
instead.
So let's do that:
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.blue)
.clipShape(RoundedRectangle(cornerRadius: 20))
While the result looks the same, the code is now more verbose and harder to read.
There is, however, a convenience method on Shape
that allows us to simplify this a bit:
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.blue)
.clipShape(.rect(cornerRadius: 20))
This is a bit better, but still not as nice as the original cornerRadius
modifier.
Bring back cornerRadius
So how can we bring back the cornerRadius
modifier? Well, we can simply create our own view modifier that wraps the clipShape
modifier:
struct CornerRadiusViewModifier: ViewModifier {
let radius: Double
func body(content: Content) -> some View {
content.clipShape(.rect(cornerRadius: radius))
}
}
extension View {
func cornerRadius(_ radius: Double) -> some View {
modifier(CornerRadiusViewModifier(radius: radius))
}
}
Congratulations, you have now brought back the cornerRadius
modifier. You can now use it like you used to:
While this is the method Apple suggests, it introduces a lot of boilerplate code. So let's see if we can simplify this a bit. We can simply put the clipShape
modifier into the extension on View
:
extension View {
func cornerRadius(_ radius: Double) -> some View {
clipShape(.rect(cornerRadius: radius))
}
}
Which method you choose is totally up to you. I personally prefer to use the first method. It is a bit more verbose, but it is the way Apple suggests to do it in their documentation.
Conclusion
As you can see it is pretty easy to bring back the cornerRadius
modifier. I hope that Apple will reconsider this decision and bring back the cornerRadius
modifier in a future version of SwiftUI. Until then, you can use the method described above.
If you have any questions or feedback, feel free to reach out to me on X (Twitter).
Also make sure to checkout some other articles I have written about SwiftUI below.