Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of the corner radius of widget in SwiftUI?

enter image description here enter image description here

I want to maintain the same inset around my custom view. Exterior corner radius is required to change the corner radius of our custom views,

I could not find any environment variable or any other way to get the corner radius of the widget itself.

  • Just parsing a hardCoded value to .cornerRadius() is not work on every device. Since different devices may use a different radius for their widgets.
    var body: some View {
            VStack {
                HStack {
                    VStack {
                        Text("Hello")
                            .font(.title)
                        Text("Widget")
                    }
                    .padding()
                    .background(Color.yellow)
                    .cornerRadius(10)//<=here
                    Spacer()
                }
                Spacer()
            }
            .padding(5.0)
        }

like image 795
Yodagama Avatar asked Jan 10 '21 15:01

Yodagama


Video Answer


1 Answers

We have a much better way to do this in iOS 14 using the ContainerRelativeShape.

ContainerRelativeShape is a new shape type that will take on the path of the nearest container shape specified by a parent with an appropriate corner radius based on the position of the shape.

In this instance, the system is defining the container shape for our widget, and we get the corner radius concentric with it super easy.

.background(ContainerRelativeShape().fill(Color.yellow))
    var body: some View {
        VStack {
            HStack {
                VStack {
                    Text("Hello")
                        .font(.title)
                    Text("Widget")
                }
                .padding()
                .background(ContainerRelativeShape().fill(Color.yellow)) //<=here
                Spacer()
            }
            Spacer()
        }
        .padding(5.0)
    }
like image 158
Yodagama Avatar answered Oct 15 '22 10:10

Yodagama