繁体   English   中英

SwiftUI, IF 在 ForEach 循环内显示不同的文本

[英]SwiftUI, IF inside ForEach loop to display different text

我很难在 SwiftUI 的 ForEach 循环中显示某些文本。

我有一个用 ForEach 迭代的数组。 问题是,我需要显示某些文本,以确定是否在日历中选择了特定日期。 例如:

ForEach(reminders) { reminder in 
    if(Calendar.current.isDate(reminder.beginDate, equalTo: selectedPassedDate) {
       HStack {
         Text("The Text for the specific day")
       } else {
         Text("The text for the unspecific day")
       }
    }
}

当数组有超过 2 个元素时,不匹配日期的文本会显示多次(因为它在 foreach 内)。 这是有道理的,但我试图找出一种只显示一个“未指定日期”文本而不是许多文本的方法。

我尝试添加一个简单的布尔值来显示其他文本,但我无法在没有按钮或其他东西的情况下更改它的 state。我需要完全以编程方式完成此操作。 我还将 else 语句移到了循环之外,但次要文本再次显示在当前日期选择中。

我能做些什么来解决这个问题? 如果我可以在符合 SwiftUIs 视图的同时以编程方式设置布尔值,那么我可以解决这个问题,但我不确定如何解决。

你可以尝试这样的事情:

class FirstTime: ObservableObject {
    var value = true
}

struct MyView: View {
    ...
    @State var firstTime = FirstTime()

    var body: some View {
    VStack {
        ForEach(reminders) { reminder in
            HStack {
                if (Calendar.current.isDate(reminder.beginDate, equalTo: selectedPassedDate) {
                    Text("The Text for the specific day")
                } else {
                    if firstTime.value {
                        showTextOnce()
                    }
                }
            }
        }
    }
}

func showTextOnce() -> some View {
    firstTime.value = false
    return Text("The text for the unspecific day")
} 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM