swiftui - SwiftUI - 获取孩子的大小?
问题描述
有没有办法在 SwiftUI 中获取子视图的大小?
我基本上希望做的 UIKit 相当于:
self.child.frame.origin.x -= self.child.intrinsicContentSize.width/2.0
我认为 GeometryReader 不会起作用,因为它会返回父级中的可用大小。
[编辑] 我发现使用它来获取和保存尺寸是可能的,.alignmentGuide(_, computeValue:)
尽管这绝对是一个 hack。
LessonSliderText(text: self.textForProgress(self.progress), color: self.completedColor)
.alignmentGuide(HorizontalAlignment.leading) { (dimensions) -> Length in
self.textSize = CGSize(width: dimensions.width, height: dimensions.height)
return 0
}
.offset(x: self.width*self.currentPercentage - self.textSize.width / 2.0)
.offset(y: -self.textSize.height/2.0)
.animation(nil)
.opacity(self.isDragging ? 1.0 : 0.0)
.animation(.basic())
解决方案
更新并概括了@arsenius 代码。现在您可以轻松绑定父视图的状态变量。
struct ChildSizeReader<Content: View>: View {
@Binding var size: CGSize
let content: () -> Content
var body: some View {
ZStack {
content()
.background(
GeometryReader { proxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: proxy.size)
}
)
}
.onPreferenceChange(SizePreferenceKey.self) { preferences in
self.size = preferences
}
}
}
struct SizePreferenceKey: PreferenceKey {
typealias Value = CGSize
static var defaultValue: Value = .zero
static func reduce(value _: inout Value, nextValue: () -> Value) {
_ = nextValue()
}
}
用法:
struct ChildSizeReaderExample: View {
@State var textSize: CGSize = .zero
var body: some View {
VStack {
ChildSizeReader(size: $textSize) {
Text("Hello I am some arbitrary text.")
}
Text("My size is \(textSize.debugDescription)!")
}
}
}
推荐阅读
- python-3.x - 从python中的日期列表中添加日期
- python - TensorFlow 异常:模块 'tensorflow.tools.api.generator.api.math' 没有属性 'log'
- apache-flex - Flex mxmlc ant 任务给出 java.lang.OutOfMemoryError: Java heap space
- scala - 如何构建多个 Spark 数据帧并并行运行?
- microsoft-graph-api - 如何将 onedrive 文件共享给组织外的人员
- go - 如何使用gorm创建到mysql的ssl连接?
- angularjs - 使用 angularjs 显示 API 内容
- linux - rc.local 的环境
- python - 无法用尽加载更多按钮来揭开所有头条新闻
- c - 拆分字符串并使用索引来调用所需的元素