我想创建属性列表(不使用列表视图)。每个属性都是一个 HStack,其中包含两个文本:名称和值。我希望名称文本始终占整个 HStack 宽度的 30%,而值文本则使用其余的水平空间。每个属性的高度取决于内容。
我尝试通过以下观点来实现它:
struct FatherList: View {
let attributes: Attributes
init(_ attributes: Attributes) {
self.attributes = attributes
}
var body: some View {
VStack(spacing: CGFloat.spacing.medium) {
ForEach(
attributes,
id: \.name,
content: ChildView.init
)
}
}
}
其中包含以下 ChildView:
struct ChildView: View {
let listItem: Product.Attribute
init(_ attribute: Product.Attribute) {
self.attribute = attribute
}
var body: some View {
GeometryReader { geometry in
HStack(alignment: .top, spacing: 0) {
Text(attribute.name)
.bold()
.frame(width: 0.3 * geometry.size.width)
.background(Color.yellow)
Text(attribute.value)
}
.fixedSize(horizontal: false, vertical: true)
.background(Color.red)
}
}
}
我得到的结果是这样的:
子视图重叠,这不是我想要的,我希望子视图展开并相互跟随。我正在使用 GeometryReader 来完成我上面描述的相对宽度。我究竟做错了什么?
这是可能解决方案的演示。使用 Xcode 11.4 / iOS 13.4 进行测试
Note: ViewHeightKey
取自这是我的另一个解决方案 https://stackoverflow.com/a/62561752/12299030
struct ChildView: View {
let attribute: Attribute
@State private var fitHeight = CGFloat.zero
var body: some View {
GeometryReader { geometry in
HStack(alignment: .top, spacing: 0) {
Text(self.attribute.name)
.bold()
.frame(width: 0.3 * geometry.size.width, alignment: .leading)
.background(Color.yellow)
Text(self.attribute.value)
.fixedSize(horizontal: false, vertical: true)
.frame(width: 0.7 * geometry.size.width, alignment: .leading)
}
.background(Color.red)
.background(GeometryReader {
Color.clear.preference(key: ViewHeightKey.self,
value: $0.frame(in: .local).size.height) })
}
.onPreferenceChange(ViewHeightKey.self) { self.fitHeight = $0 }
.frame(height: fitHeight)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)