Home > Blockchain >  How can I create custom shapes in swiftUI
How can I create custom shapes in swiftUI

Time:05-30

I'm learning swiftui and I want to create some shapes in my app.

I instead of repeating my code I decided to create a function to display the shape.

I tried to create a func that contains the shape and call it where I need it.

import SwiftUI

struct HomeView: View {
    var body: some View {
        VStack{
            HStack{
               rect()
            }
        }
    }
}

func rect() {
    Rectangle()
        .frame(width: 100, height: 100)
        .cornerRadius(18)
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}

What is my problem here, and how can I fix it so I can create different styles for buttons, textboxes, images, etc...

CodePudding user response:

You're on the right track, instead of defining a function, define a new view:

struct MyRect: View {

    var body: some View {
        Rectangle()
            .frame(width: 100, height: 100)
            .cornerRadius(18)
    }
}

// Embed with 'MyRect()'

Alternatively, the func rect in your code could have a return type some View:

func rect() -> some View {
    Rectangle()
        .frame(width: 100, height: 100)
        .cornerRadius(18)
}

// Embed with 'rect()'

CodePudding user response:

To create a function for showing the view one must create @ViewBuilder function and return some View.

You need to do something like this :-

      @ViewBuilder func rect() -> some View {
   
              Rectangle()
                  .frame(width: 100, height: 100)
                  .cornerRadius(18)

      }

CodePudding user response:

The func rect is of type Void, the body in your View returns some View. You should make your function's return type conform to View, so either:

  1. return a Shape func rect() -> Shape {

  2. return a View func rect() -> some View {

Do note that if go with option number 1 you cannot return anything that is not a Shape.

  • Related