How to display array data lined up in dates and rows in SwiftUI, in iOS14

120 Views Asked by At

I need an advice in this problem. In my design I have a check in with emotions.Here it is.

When you tap on Pass Check In you chose how do you feel and it saves it locally. I have figured out how to save it (addEmotion). I will show you the functions and model:

struct CheckIn: Codable {
    
    let timeAdded: Date
    let emotion: String
    
}

class CheckInData: ObservableObject {
    
    @Published var arrayWithEmotion: [CheckIn]? = []
    
    init() {
        arrayWithEmotion = loadEmotion()
    }
    
    func addEmotion(emotion: CheckIn) {
        arrayWithEmotion?.append(emotion)
        saveEmotion()
        print(arrayWithEmotion ?? [])
    }
    
    func saveEmotion() {
        if let encoded = try? JSONEncoder().encode(arrayWithEmotion) {
            UserDefaults.standard.set(encoded, forKey: "emotions")
        }
    }

    func loadEmotion() -> [CheckIn] {
        if let encoded = UserDefaults.standard.data(forKey: "emotions") {
            if let decoded = try? JSONDecoder().decode([CheckIn].self, from: encoded) {
                return decoded
            }
        }

        return []
    }
}


As you can see, I am saving the name and current time when it was saved. Now my task is to display it, but I have no idea how to do that in between dividers. Also I need a hint of how to line it up with dates that displayed under. The only thing I've figured out how to display it is like this (image name == emotion name, that's why I'm using it as an image):

                        if checkIn.arrayWithEmotion != nil {
                            
                            ForEach(0..<checkIn.arrayWithEmotion!.count, id: \.self) { i in
                                
                                if checkIn.arrayWithEmotion?[i].emotion == "GREAT"{
                                    
                                    withAnimation {
                                        Image(checkIn.arrayWithEmotion![i].emotion)
                                            .resizable()
                                            .frame(width: 20, height: 20)
                                            .scaledToFill()
                                    }
                                }
                            }
                            
                        }

I am not sure this is possible in SwiftUI, so if your answer will be in UIKit I won't mind.

NOTE: - In each vertical line must be only one emotion. Maybe I should rewrite my Model to save nil?

P.s.: I know that I ask just for code, but I really don't know how to do it(

0

There are 0 best solutions below