Replacing the Deprecated cornerRadius Modifier in SwiftUI
Written on
Chapter 1: Introduction to Deprecated Modifiers
In this guide, we'll explore how to substitute the now-deprecated cornerRadius modifier in SwiftUI following its removal in iOS 17.4, and discuss why the new alternative is preferable.
The deprecation of APIs can be beneficial when improved alternatives exist.
Welcome to a brief programming tip regarding a recent deprecation within SwiftUI. Until the release of iOS 17.4, the cornerRadius(_:) view modifier was the simplest way to round off the corners of any view, enhancing its aesthetic appeal. Implementing it was quite straightforward, requiring just a radius value as an argument. However, with iOS 17.4, the cornerRadius(_:) modifier has been deprecated, prompting a need for change.
To illustrate, consider the following code snippet that demonstrates a color view with a defined frame and the cornerRadius modifier applied:
Color.indigo
.frame(width: 250, height: 200)
.cornerRadius(24)
If you attempt to use ".cornerRadius" in Xcode, you'll encounter a warning indicating its deprecation. Despite its popularity, it's time to move on.
Section 1.1: Transitioning to clipShape Modifier
So, how can we effectively replace it?
The most efficient method is to utilize the clipShape(_:) view modifier. This modifier accepts a shape object as an argument and clips the target view to that shape. Among the various built-in shapes available in SwiftUI, the RoundedRectangle is the ideal candidate, accepting a radius value similar to the now-deprecated cornerRadius(_:) modifier.
Here's how you can modify the previous code to incorporate the clipShape(_:) modifier along with the RoundedRectangle(cornerRadius:) shape:
Color.indigo
.frame(width: 250, height: 200)
// This replaces the cornerRadius(_:) view modifier.
.clipShape(RoundedRectangle(cornerRadius: 12))
Subsection 1.1.1: Advantages of Using clipShape
The clipShape(_:) modifier is an excellent alternative, offering the flexibility to clip a view using any shape, whether built-in or custom, not just limited to the RoundedRectangle.
Section 1.2: Conclusion
Now you know how to round corners in SwiftUI without relying on the deprecated cornerRadius(_:) modifier. While I frequently utilized it, the introduction of clipShape(_:) made its obsolescence inevitable.
Chapter 2: Video Explanation
In this video titled "cornerRadius Deprecated in SwiftUI - Xcode 15 (iOS Development)", you'll find a detailed explanation of the changes and learn how to adapt your code effectively.