【发布时间】:2020-11-13 19:37:35
【问题描述】:
经过多次搜索,我似乎无法找到解决方案。我正在尝试在函数调用addDay 中更新我的状态变量d。这个函数在 ForEach 循环中被调用。问题是,d 一次更新为 2.0 的值,然后它永远保持在 2.0。我不确定出了什么问题,有什么见解吗?
let weekdays: [String] = ["Mon", "Tues", "Wed", "Thurs", "Fri"]
@State var startDate: Date = Date().next(.monday, direction: .backward)
@State var d:Double = 1.0
/**
- parameter startDate: the beginning date that will be modified
- Returns: A new Text that has a date attached
*/
func addDay(startDate: Date) -> Text {
self.startDate = startDate.addingTimeInterval(86400 * self.d)
self.d += 1.0
return Text("\(startDate, formatter: Self.weekFormat)")
}
static let weekFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd"
return formatter
}()
var body: some View {
ScrollView(.horizontal) {
HStack{
ForEach(weekdays, id: \.self) { weekday in
VStack{
RoundedRectangle(cornerRadius: 9, style: .continuous)
.stroke(Color.blue)
.frame(width: 68.5, height: 68.5)
self.addDay(startDate: self.startDate)
Text(String(self.d))
Text(weekday)
}
}
}
}
}
}
【问题讨论】: