本文介绍了SwiftUI:如何在不使用几何阅读器的情况下根据框架的大小计算视图的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码效果很好,但是几何读取导致我在上游出现问题,所以我希望有相同的逻辑来根据可用空间构建视图的宽度,但不使用几何读取器.可能吗?
The below code works great, however the geometry reading is causing me issues upstream, so I would like to have the same logic to build the view's width based on available space but without using Geometry Reader. Is it possible?
var body: some View {
ZStack {
GeometryReader { geometry in
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 12.0)
.fill(Color(.lightGray))
.opacity(0.1)
.frame(height: 20)
RoundedRectangle(cornerRadius: 12.0)
.fill(getColorForBar(progress: progress))
.frame(width: getFillWidth(progress: progress, geometry: geometry), height: 20)
.animation(self.progressAnimation)
}
}
}
}
private func getFillWidth(progress: Double, geometry: GeometryProxy) -> CGFloat {
var offset: CGFloat = geometry.size.width * CGFloat(progress)
if progress == 0 {
offset = (geometry.size.width * CGFloat(progress)) + 10.0
} else if progress == 1.0 {
offset = (geometry.size.width * CGFloat(progress)) - 10.0
}
return offset
}
推荐答案
GeometryReader
实际上是读取视图几何的精确工具.你只需要以不同的方式使用它(所以不影响外部布局).
The GeometryReader
is exact instrument to read views geometry, actually. You just need to use it in different way (so not affect external layout).
这是一个不破坏布局的解决方案.使用 Xcode 12.1/iOS 14.1 测试
Here is a solution that do not break layout. Tested with Xcode 12.1 / iOS 14.1
RoundedRectangle(cornerRadius: 12.0) // << this consumes available width only
.fill(Color(.lightGray))
.opacity(0.1)
.frame(height: 20)
.overlay(GeometryReader { geometry in // << this reads parent rectangle area
RoundedRectangle(cornerRadius: 12.0)
.fill(getColorForBar(progress: progress))
.frame(width: getFillWidth(progress: progress, geometry: geometry), height: 20)
.animation(self.progressAnimation)
}, alignment: .leading)
这篇关于SwiftUI:如何在不使用几何阅读器的情况下根据框架的大小计算视图的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!