Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Circular View in SwiftUI
Written by Team Kodeco

Do you want to create a stylish circular view in SwiftUI? Well, it’s quite simple to achieve this using built-in view modifiers. In SwiftUI, you can transform the shape of a view easily by using predefined shapes, such as Circle, Capsule or Rectangle.

To create a circular view, you just have to use the Circle shape and adjust its properties.

struct ContentView: View {
  var body: some View {
    Text("Hello,\nCircular View!")
      .multilineTextAlignment(.center)
      .padding(50)
      .foregroundColor(.white)
      .background(Circle().fill(.blue))
  }
}

The preview for this view should look as follows:

A circular view in SwiftUI.
A circular view in SwiftUI.

In the above example, you used the Circle shape as the background of the text view. You also provided a fill modifier to the Circle shape, which fills it with the blue color.

Further, you have given some padding to the text view and set its text color to white. The resulting view is a circular blue background with white text shown inside the circle.

If you want to change the size of the circular view, you can adjust the frame modifier of the Circle shape.

struct ContentView: View {
  var body: some View {
    Text("Hello,\nCircular View!")
      .multilineTextAlignment(.center)
      .padding(50)
      .foregroundColor(.white)
      .background(
        Circle()
          .fill(Color.blue)
          .frame(width: 200, height: 200)
      )
  }
}

The preview for this view should now look as follows:

A circular view in SwiftUI.
A circular view in SwiftUI.

In the above example, we have given a fixed size of width and height as 200 points to the frame modifier of the Circle shape. This will result in a circular view with a 200-point diameter.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.