当@Published被更新时文本不更新



我有一个视图,其中包含一周中的天数,当用户切换箭头时,它应该增加(增加到下一天或前一天)。

首先获取当前星期几并格式化为String。然后保存到var currentWeekday:

class GrabCurrentDate: ObservableObject {
@Published var currentWeekday = Date().dayNumberOfWeek()!

func currentDate() {
let date = Date()
let formatter = DateFormatter()
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())
//set day of week
currentWeekday = Date().dayNumberOfWeek()!
}
}

然后在switch语句中转储一周中的天数,并将要在视图中显示的天数分配为字符串:

extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday! - 1
}
}
func weekdayAsString(date: Int) -> String {
switch Date().dayNumberOfWeek() {
case 0:

return "Sunday"

case 1:
return "Monday"

case 2:
return "Tuesday"

case 3:
return "Wednesday"

case 4:
return "Thursday"

case 5:
return "Friday"

case 6:
return "Saturday"

default:
return ""
}
}

最后我的观点:

struct testView: View {
@ObservedObject var currentDate = GrabCurrentDate()
func weekdayAsString(date: Int) -> String {
// Defined in the code above
}
var body: some View {
HStack {
Image(systemName: "arrow.left")
.onTapGesture{
currentDate.currentWeekday -= 1
print(currentDate.currentWeekday )
}
Text(weekdayAsString(date: currentDate.currentWeekday)) // << display current day of week

Image(systemName: "arrow.right")
.onTapGesture{
currentDate.currentWeekday += 1
}
}
}
}

当我去增量,发布的var更新正确,但视图没有。提前感谢您的帮助。

也许这能帮到你:

enum Weekday: String, CaseIterable {
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}
class CurrentDate: ObservableObject {

@Published private(set) var currentDay: Int = Date().currentDay

var currentWeekday: Weekday {
Weekday.allCases[currentDay - 1]
}

func increment() {
// check if the currentDay is within the range
currentDay += 1
}

func decrement() {
currentDay -= 1
}

}
extension Date {

var currentDay: Int {
return Calendar.current.component(.weekday, from: self)
}
}
struct ContentView: View {

@StateObject private var currentDate = CurrentDate()

var body: some View {
NavigationStack {
VStack {
Text(currentDate.currentWeekday.rawValue.capitalized)
Button("Next") {
currentDate.increment()
}
}
}
}
}

你是NOT使用currentDate.currentWeekdayweekdayAsString中的函数。在开关中,您使用的是Date(). daynumberofweek ()。因此只需将其更改为参数date:

func weekdayAsString(date: Int) -> String {
switch date {
case 0:
return "Sunday"
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
default:
return ""
}
}
我还建议您使用按钮而不是带有onTapGesture手势的图像,像这样:
Button {
currentDate.currentWeekday += 1
print(currentDate.currentWeekday )
} label: {
Image(systemName: "arrow.right")
}

如果你喜欢,你也可以用原色显示它们:

Button {
currentDate.currentWeekday += 1
print(currentDate.currentWeekday )
} label: {
Image(systemName: "arrow.right")
}
.foregroundColor(.primary)

最新更新