| |

How to Add Border with Rounded Corners to ZStack in iOS SwiftUI

Building an intuitive and eye-catching user interface requires proficiency in manipulating your SwiftUI views. One such view is the ZStack, allowing layered alignment of views. In this guide, we delve into creating a border with rounded corners for your ZStack.

ZStack Overview

ZStack is an essential component in SwiftUI. It stacks its child views along the z-axis, creating a layered visual effect. Utilizing it effectively can add a considerable amount of visual depth to your app.

Create ZStack Border with Rounded Corners

To add a border with rounded corners to a ZStack, we will use the .overlay and .padding modifiers along with the RoundedRectangle view.

Step 1: Initialize a ZStack

Start by initializing a ZStack. Add a Text view to visualize the stacking.

ZStack {
  Text("Hello ZStack!")
}

Step 2: Add Padding

Padding is essential for providing spacing around the ZStack content. The .padding modifier gives the content some room to breathe.

ZStack {
  Text("Hello ZStack!")
}.padding()

Step 3: Create the Border

For the border, we’ll use the .overlay modifier along with a RoundedRectangle view. Set the cornerRadius and color in the RoundedRectangle constructor, and specify the lineWidth for the .stroke modifier.

ZStack {
  Text("Hello ZStack!")
}.padding()
  .overlay(RoundedRectangle(cornerRadius: 30)
    .stroke(Color.blue, lineWidth: 2))
swiftui zstack rounded corners

The ZStack is an integral part of SwiftUI. By combining it with other views and modifiers, you can create complex and visually appealing UI elements, like a border with rounded corners. Now, your SwiftUI toolbelt is more robust, and you’re ready to create dynamic, layered interfaces.

Similar Posts

Leave a Reply