简体   繁体   中英

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

在此处输入图像描述 在此处输入图像描述

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)
        }

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM