SwiftUI - 获取孩子的大小? [英] SwiftUI - Get size of child?
本文介绍了SwiftUI - 获取孩子的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 SwiftUI 中获取子视图的大小?
Is there any way to get the size of a child view in SwiftUI?
我基本上想做 UIKit 等效于:
I'm basically looking to do the UIKit equivalent of:
self.child.frame.origin.x -= self.child.intrinsicContentSize.width/2.0
我不认为 GeometryReader 会起作用,因为它返回父级中的可用大小.
I don't think a GeometryReader would work since that returns the available size in the parent.
我发现可以使用 .alignmentGuide(_, computeValue:)
获取和保存尺寸,尽管这绝对是一个黑客.
I've found it's possible to get and save the dimensions using .alignmentGuide(_, computeValue:)
though that's definitely a 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())
推荐答案
基本上,此时的答案是使用 GeometryReader
inside 孩子的 background(...)
修饰符.
Basically, the answer at this point is to use a GeometryReader
inside of the child's background(...)
modifier.
// This won't be valid until the first layout pass is complete
@State var childSize: CGSize = .zero
var body: some View {
ZStack {
Text("Hello World!")
.background(
GeometryReader { proxy in
Color.clear
.preference(
key: SizePreferenceKey.self,
value: proxy.size
)
}
)
}
.onPreferenceChange(SizePreferenceKey.self) { preferences in
self.childSize = preferences
}
}
struct SizePreferenceKey: PreferenceKey {
typealias Value = CGSize
static var defaultValue: Value = .zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
这篇关于SwiftUI - 获取孩子的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文