如何在 SwiftUI 中获取小部件的圆角半径的大小? [英] How to get the size of the corner radius of widget in SwiftUI?

查看:83
本文介绍了如何在 SwiftUI 中获取小部件的圆角半径的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的自定义视图周围保持相同的插图.需要外部拐角半径来更改我们的自定义视图的拐角半径,

我找不到任何环境变量或任何其他方式来获取小部件本身的拐角半径.

  • 仅将硬编码值解析为 .cornerRadius()并非在所有设备上都有效.自从不同的设备可能对其小部件使用不同的半径.

  var正文:某些视图{VStack {HStack {VStack {文字("Hello").font(.title)文字(小部件")}.填充().background(颜色.黄色).cornerRadius(10)//< =这里垫片()}垫片()}.padding(5.0)} 

解决方案

iOS 14 中,我们有一种更好的方法,就是使用 ContainerRelativeShape .>

ContainerRelativeShape 是一种新的形状类型,它将采用由父级指定的最接近的容器形状的路径,并根据形状的位置指定适当的拐角半径

在这种情况下,系统为小部件定义了容器形状,并且使角半径与它同心非常容易.

  .background(ContainerRelativeShape().fill(Color.yellow)) 

  var正文:某些视图{VStack {HStack {VStack {文字("Hello").font(.title)文字(小部件")}.填充().background(ContainerRelativeShape().fill(Color.yellow))//< =这里垫片()}垫片()}.padding(5.0)} 

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

这篇关于如何在 SwiftUI 中获取小部件的圆角半径的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆