在SwiftUI中使用获取视图的宽度 [英] Get width of a view using in 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 return the dimensions of the container.
什么是几何读取器?该文档说:
What is a geometry reader? the documentation says:
根据其自身大小和坐标空间定义其内容的容器视图. 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:
阅读更多示例:
- Make a VStack fill the width of the screen in SwiftUI
- How to make view the size of another view in SwiftUI
这篇关于在SwiftUI中使用获取视图的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!