我无法弄清楚为什么我的 ForEach 循环使我的视图无法在其父视图中正确缩放。如果我注释掉 ForEach 循环并取消注释//.frame(width: geometry.size.width, height: 10)
RoundedRectangle 在其父视图中正确缩放,但是当使用 ForEach 循环时,我的视图会流出屏幕。我已经仔细检查了CGFloat((sleepOrAwakeSpan.seconds / DataStore.sleepOrAwakeSpans.map { $0.endTime.timeIntervalSince($0.startTime) }.reduce(0, +)))
总数 = 100。所以我知道几何是正确的,并且我知道我预期的几何百分比是正确的,什么可能导致添加 ForEach 使其流出屏幕?
struct AsleepTimeView: View {
@EnvironmentObject var dataStore: DataStore
static let sleepTimeFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
var body: some View {
Color.clear.overlay(
GeometryReader { geometry in
VStack(alignment: .center) {
HStack {
ForEach(DataStore.sleepOrAwakeSpans) { sleepOrAwakeSpan in
RoundedRectangle(cornerRadius: 5)
.frame(width: geometry.size.width * CGFloat((sleepOrAwakeSpan.seconds / DataStore.sleepOrAwakeSpans.map { $0.endTime.timeIntervalSince($0.startTime) }.reduce(0, +))), height: 10)
//.frame(width: geometry.size.width, height: 10)
.foregroundColor(sleepOrAwakeSpan.asleep == false ? TrackerConstants.scaleLevel6Color : TrackerConstants.scaleLevel2Color)
//.foregroundColor(.red)
}
}
}
}) // end of overlay
}
}