[英]SwiftUI Make parent view stretch to fit child view
I have a list of navigation views, where each item in the list has a title, 2 rows of sub text, and a partially filled rectangle.我有一个导航视图列表,其中列表中的每个项目都有一个标题、2 行子文本和一个部分填充的矩形。 The rows look how I want, however the list items aren't big enough to fit the entire view, so they are flowing outside and overlapping each other.
行看起来像我想要的那样,但是列表项不够大以适合整个视图,因此它们向外流动并相互重叠。 Here is a sample of what it looks like:
这是它的外观示例:
So how can i get the list items to expand to the size of their children?那么我怎样才能让列表项扩展到他们孩子的大小呢?
Here is my code:这是我的代码:
struct ItemDetials {
let title: String
let rowOne: String
let rowTwo: String
let stat: Double
let maxOfStat: Double
let color: UIColor
}
struct ItemDetailsRowView: View {
var itemDetails: ItemDetials
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
Rectangle().frame(width: geometry.size.width * itemDetails.stat/itemDetails.maxOfStat,
height: geometry.size.height)
.opacity(0.3)
.foregroundColor(Color(itemDetails.color))
HStack {
VStack(alignment: .leading) {
Text(itemDetails.title)
.font(.system(size: 20))
Text(itemDetails.rowOne)
.font(.system(size: 12))
.foregroundColor(.gray)
Text(itemDetails.rowTwo)
.font(.system(size: 12))
.foregroundColor(.gray)
}
}
}
}
}
}
struct ItemDetailsRowView_Previews: PreviewProvider {
static var previews: some View {
let details: [ItemDetials] = [
ItemDetials(
title: "Test Title",
rowOne: "Some info about row",
rowTwo: "Some more info",
stat: 0.6,
maxOfStat: 1.0,
color: .red
),
ItemDetials(
title: "Test Title 2",
rowOne: "Some info about row 2",
rowTwo: "Some more info 2",
stat: 0.2,
maxOfStat: 1.0,
color: .green
),
ItemDetials(
title: "Test Title 3",
rowOne: "Some info about row 3",
rowTwo: "Some more info 3",
stat: 0.8,
maxOfStat: 1.0,
color: .blue
)
]
VStack {
let withIndex = details.enumerated().map({ $0 })
List {
ForEach(withIndex, id: \.element.title) { index, _ in
NavigationLink(destination: Text("Sup"), label: {
ItemDetailsRowView(itemDetails: details[index])
})
}
}
}
}
}
Instead of wrapping the entire ZStack
with the GeometryReader
, wrap only the Rectangle
where you need the size:而不是用
GeometryReader
包裹整个ZStack
,只包裹你需要大小的Rectangle
:
struct ItemDetailsRowView: View {
var itemDetails: ItemDetials
var body: some View {
ZStack(alignment: .leading) {
GeometryReader { geometry in
Rectangle().frame(width: geometry.size.width * itemDetails.stat/itemDetails.maxOfStat,
height: geometry.size.height)
.opacity(0.3)
.foregroundColor(Color(itemDetails.color))
}
HStack {
VStack(alignment: .leading) {
Text(itemDetails.title)
.font(.system(size: 20))
Text(itemDetails.rowOne)
.font(.system(size: 12))
.foregroundColor(.gray)
Text(itemDetails.rowTwo)
.font(.system(size: 12))
.foregroundColor(.gray)
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.