如何使 SwiftUI 视图按时间顺序显示项目并保持绑定?

huangapple go评论64阅读模式
英文:

How can I get a SwiftUI view to display items in chronological order and maintain bindings?

问题

我试图按照时间顺序显示一个日期列表,同时使用@Binding(这些日期都存储在一个名为[DatesInfo]的数组中,我认为这是真实数据源)

struct DatesView: View {
    @Binding var dates: [DatesInfo]

    var body: some View {
        List{
            ForEach($dates, editActions: .delete) { $date in
                CardView(thisDate: date)
            }
            .background(NavigationLink("", destination: DetailView(thisDate: $date)).opacity(0))
        }
    }
}

我已经看到如何按日期排序列表,但我无法使它们与导航链接所需的绑定一起工作。

英文:

I'm trying to display a list of dates in chronological order whilst using @Binding (The dates are all stored in an array called [DatesInfo] which I believe is the source of truth)

struct DatesView: View {
    @Binding var dates: [DatesInfo]

    var body: some View {
        List{
            ForEach($dates, editActions: .delete) { $date in
                CardView(thisDate: date)
            }
            .background(NavigationLink("", destination: DetailView(thisDate: $date)).opacity(0))
        }
    }
}

I've seen how to order a list by date however I can't get them to work with the bindings needed for the Navigation link thing.

答案1

得分: 0

>更多信息,请阅读这篇文章 Apple文档 或这个 链接

struct DatesView: View {
    @Binding var dates: [DatesInfo]

    var sortedDates: [DatesInfo] {
        dates.sorted {
            $0.date < $1.date
        }
    }

    var body: some View {
        List {
            ForEach(sortedDates, id: \.id) { date in
                CardView(thisDate: date)
                    .background(
                        NavigationLink("", destination: DetailView(thisDate: $dates[dates.firstIndex(of: date)!]))
                            .opacity(0)
                    )
            }
        }
    }
}
英文:

>For more information, you can read this article Apple Documentation or this link

struct DatesView: View {
        @Binding var dates: [DatesInfo]

    var sortedDates: [DatesInfo] {
        dates.sorted { 
            $0.date < $1.date 
        }
    }

    var body: some View {
        List {
            ForEach(sortedDates, id: \.id) { date in
                CardView(thisDate: date)
                    .background(
                        NavigationLink("", destination: DetailView(thisDate: $dates[dates.firstIndex(of: date)!]))
                            .opacity(0)
                    )
            }
        }
    }
}

huangapple
  • 本文由 发表于 2023年4月19日 23:08:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定