In this SwiftUI tutorial, I am going to show you some examples of making the corners of a view rounded.
There are three modifiers we can use to make the corners of any view round. Below are given these 3 modifiers:
Now let’s see how to use each modifier one by one to give corners of view a rounded shape.
cornerRadius
The simplest way to create rounded corners for a view is by using the cornerRadius modifier. We just apply this modifier and provide the value in point. This value controls how pronounced the rounding should be to the view. It will be the amount of the corner radius.
Below is an example of applying it to a SwiftUI text view:
Text("Hello World")
.padding()
.background(.green)
.foregroundColor(.white)
.cornerRadius(24)
clipShape
modifier to make corners roundThe clipShape
modifier also can be used to make the corners round. Using this modifier, you can set a clipping shape for the view. There are a number of built-in shapes available in SwiftUI to make rounded corners.
Below is an example where we use the RoundedRectangle
for clipShape
modifier to create rounded corners:
Text("Hello World")
.padding()
.background(.green)
.foregroundColor(.white)
.clipShape(
RoundedRectangle(
cornerRadius: 18
)
)
In the above example, we have set the corner radius value to 18 for RoundedRectangle
.
You can also set the continuous style to the RoundedRectangle to make the rounded corners smooth:
Text("Hello World")
.padding()
.background(.green)
.foregroundColor(.white)
.clipShape(
RoundedRectangle(
cornerRadius: 18,
style: .continuous
)
)
We can also use the Capsule()
to provide a capsule shape as it already has rounded corners. Capsule is the built-in shape in SwiftUI. Below is how to use it with clipShape
modifier:
background
modifierYou can use the same RoundedRectangle
or Capsule
shape with the background modifier to create rounded corners. But here, you can fill it with color using the fill
modifier.
Below are given three examples:
VStack {
Text("Learn SwiftUI")
.padding()
.foregroundColor(.white)
.background(
RoundedRectangle(cornerRadius: 22)
.fill(.black)
)
Text("Learn SwiftUI")
.padding()
.foregroundColor(.white)
.background(
Capsule()
.fill(.blue)
)
Text("Learn SwiftUI")
.padding()
.foregroundColor(.white)
.background(
RoundedRectangle(
cornerRadius: 20,
style: .continuous
)
.fill(.green)
)
}