返回了一个用户数组。我想按创建日期分组,然后在SwiftUI列表中显示它们。章节标题是日期。在对用户进行分组之后,我最终得到了一个用户数组的字典,键是对在同一日期创建的所有用户进行分组的日期,我想将键用作部分,并将值(用户数组)用作列表行。List似乎只适用于array。是否有任何干净的解决方案来为List准备数据,以便它可以显示部分及其内容?
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject var interactor: Interactor
var body: some View {
List(interactor.users) { user in // Error: Cannot convert value of type '[String : [User]]' to expected argument type 'Range<Int>'
}
.onAppear {
interactor.loadUsers()
}
}
}
class Interactor: ObservableObject {
@Published private(set) var users = [String: [User]]()
func loadUsers() {
let allUsers = [User(id: "1", name: "Joe", createdAt: Date()),
User(id: "2", name: "Jak", createdAt: Date())]
users = Dictionary(grouping: allUsers) { user in
let dateFormatted = DateFormatter()
dateFormatted.dateStyle = .short
return dateFormatted.string(from: user.createdAt)
}
}
}
struct User: Identifiable {
let id: String
let name: String
let createdAt: Date
}
您可以在List
中使用section,并使用其头参数传递日期。我已经通过使用单独的函数将所有日期获取为[String]
。你需要弄清楚的一件事是你将如何传递多个键来获取不同日期键的数据。也许你可以先用[Users]
对象创建,然后保存所有的键。
下面是你的问题的解决方案-:
ContentView -:
//// Created by TUSHAR SHARMA on 06/02/21.
////
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var interactor: Interactor
var body: some View {
List {
ForEach(getAllDates(),id:.self) { dates in
Section(header: Text(dates)) {
ForEach(interactor.users[dates] ?? []) { users in
Text(users.name)
}
}
}
}
}
func getAllDates() -> [String]{
let getObjects = interactor.users[Date().stringFromDate()] ?? []
var dateArray : [String] = []
for getData in getObjects{
dateArray.append(getData.createdAt.stringFromDate())
}
let unique = Array(Set(dateArray))
return unique
}
}
extension Date{
func stringFromDate() -> String{
let dateFormatted = DateFormatter()
dateFormatted.dateStyle = .short
return dateFormatted.string(from: self)
}
}
class Interactor: ObservableObject {
@Published private(set) var users = [String: [User]]()
init() {
loadUsers()
}
func loadUsers() {
let allUsers = [User(id: "1", name: "Joe", createdAt: Date()),
User(id: "2", name: "Jak", createdAt: Date())]
users = Dictionary(grouping: allUsers) { user in
user.createdAt.stringFromDate()
}
}
}
struct User: Identifiable {
let id: String
let name: String
let createdAt: Date
}
<<p>@main视图/strong>// Created by TUSHAR SHARMA on 07/01/21.
//
import SwiftUI
@main
struct WaveViewApp: App {
let interactor = Interactor()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(interactor)
}
}
}