我創建了 ListView,它用 5 個元素表示 HStack:
var body: some View {
GeometryReader { geo in
HStack(alignment: .center) {
renderHomeListItem(value: "\(title)", color: .black)
.frame(width: geo.size.width * 0.3)
renderHomeListItem(value: "\(confirmed)", color: Color(UIColor.systemRed))
.frame(width: geo.size.width * 0.15)
renderHomeListItem(value: "\(active)", color: Color(UIColor.systemBlue))
.frame(width: geo.size.width * 0.15)
renderHomeListItem(value: "\(recovered)", color: Color(UIColor.systemGreen))
.frame(width: geo.size.width * 0.15)
renderHomeListItem(value: "\(deaths)", color: Color(UIColor.systemGray))
.frame(width: geo.size.width * 0.15)
}
.fixedSize()
}
}
renderHomeListItem代表 HStack 中的一個元素:
@ViewBuilder
private func renderHomeListItem(value: String, color: Color) -> some View {
Text(value)
.padding()
.commonFont(firstListItem == true ? .bold : .regular, style: .caption2)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.foregroundColor(firstListItem == true ? color : .black)
.background(colorScheme == .light ? Color(UIColor.systemGray5) : itemDarkModeBackground)
.cornerRadius(5)
}
我這樣呼叫 ListView :
@ViewBuilder
private func renderHomeList() -> some View {
LazyVStack {
HomeListItemView(title: homeViewModel.useCaseSelection == .worldwide ? "State" : "Date", confirmed: "C", active: "A", deaths: "D", recovered: "R")
ForEach(homeViewModel.homeScreenDomainItem.listStats) { value in
HomeListItemView(title: value.title,
confirmed: "\(value.confirmed.formatUsingAbbrevation())",
active: "\(value.active.formatUsingAbbrevation())",
deaths: "\(value.deaths.formatUsingAbbrevation())",
recovered: "\(value.recovered.formatUsingAbbrevation())")
}
}
.padding()
}
問題是 ForEach 中元素的高度相互迭代,所以我得到這樣的結果:

我試圖在任何地方使用padding(),但這不是答案。
uj5u.com熱心網友回復:
那是因為GeometryReader.
最簡單的解決方案,如果它適用于您的布局,是固定的大小GeometryReader:
var body: some View {
GeometryReader { geo in
HStack(alignment: .center) {
// renderHomeListItem x 5
}
.fixedSize()
}
// This will avoid the overlaps
.frame(height: someValueHere)
}
否則,如果無法固定高度,則需要移動GeometryReader包裹整個LazyVStack然后傳遞geo給HomeListItemView。
像這樣(非常示意圖):
private func renderHomeList() -> some View {
// Delete the GeometryReader from the HomeListItemView and move it here at the top
GeometryReader { geo in
LazyVStack {
// Create a new parameter in HomeListItemView to pass the geo variable
HomeListItemView(geometry: geo, title: homeViewModel.useCaseSelection == .worldwide ? "State" : "Date", confirmed: "C", active: "A", deaths: "D", recovered: "R")
ForEach(homeViewModel.homeScreenDomainItem.listStats) { value in
// Create a new parameter in HomeListItemView to pass the geo variable
HomeListItemView(geometry: geo, title: value.title,
confirmed: "\(value.confirmed.formatUsingAbbrevation())",
active: "\(value.active.formatUsingAbbrevation())",
deaths: "\(value.deaths.formatUsingAbbrevation())",
recovered: "\(value.recovered.formatUsingAbbrevation())")
}
}
.padding()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452929.html
標籤:迅速
