在 SwiftUI 中使用获取视图的宽度 [英] Get width of a view using in SwiftUI

查看:37
本文介绍了在 SwiftUI 中使用获取视图的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 SwiftUI 中获取渲染视图的宽度,这显然不是那么容易.

I need to get width of a rendered view in SwiftUI, which is apparently not that easy.

在我看来,我需要一个返回视图尺寸的函数,就这么简单.

The way I see it is that I need a function that returns a view's dimensions, simple as that.

var body: some View {
    VStack(alignment: .leading) {
        Text(timer.name)
            .font(.largeTitle)
            .fontWeight(.heavy)
        Text(timer.time)
            .font(.largeTitle)
            .fontWeight(.heavy)
            .opacity(0.5)
    }
}

推荐答案

获得 View 尺寸的唯一方法是使用 GeometryReader.读取器返回容器的尺寸.

The only way to get the dimensions of a View is by using a GeometryReader. The reader returns the dimensions of the container.

什么是几何阅读器?文档说:

What is a geometry reader? the documentation says:

一个容器视图,将其内容定义为其自身大小和坐标空间的函数.Apple 文档

A container view that defines its content as a function of its own size and coordinate space. Apple Doc

所以你可以通过这样做得到尺寸:

So you could get the dimensions by doing this:

struct ContentView: View {
    
   @State var frame: CGSize = .zero
    
    var body: some View {
        HStack {
            GeometryReader { (geometry) in
                self.makeView(geometry)
            }
        }
        
    }
    
    func makeView(_ geometry: GeometryProxy) -> some View {
        print(geometry.size.width, geometry.size.height)

        DispatchQueue.main.async { self.frame = geometry.size }

        return Text("Test")
                .frame(width: geometry.size.width)
    }
}

打印出来的尺寸是HStack的尺寸,它是内部视图的容器.

The printed size is the dimension of the HStack that is the container of inner view.

您可能会使用另一个 GeometryReader 来获取内部尺寸.

You could potentially using another GeometryReader to get the inner dimension.

但请记住,SwiftUI 是一个声明式框架.所以你应该避免计算视图的尺寸:

But remember, SwiftUI is a declarative framework. So you should avoid calculating dimensions for the view:

阅读更多示例:

这篇关于在 SwiftUI 中使用获取视图的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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