-
I have 2 structs for the data to be passed to the tableView:
struct Session { let dateModel: Date? let timeBegModel: Date? let timeEndModel: Date? let sessionModel: String? let venueModel: String? var formattedTimeBeg: String { guard let text = timeBegModel else { return "" } return DateFormatter.adjustedTimeFormat.string(from: text) } var formattedTimeEnd: String { guard let text = timeEndModel else { return "" } return DateFormatter.adjustedTimeFormat.string(from: text) } }
-
The data is passed from another viewController with unwind segue:
@IBAction func unwindToMainVC(segue: UIStoryboardSegue) { guard let vc = segue.source as? AddSessionVC else { return } guard let date = vc.dateDP?.date, let timeBeg = vc.timeBegDP?.date, let timeEnd = vc.timeEndDP?.date, let session = vc.sessionTF.text, let venue = vc.venueTF.text else { return } let Session = Session(dateModel: date, timeBegModel: timeBeg, timeEndModel: timeEnd, sessionModel: session, venueModel: venue) sessions.append(Session) sessions.sort { $0.timeBegModel! < $1.timeEndModel! } sortByDate() // I tried to put this func in the viewDidLoad(), but it doesn't work tableView.reloadData() }
-
I have a function to set up the date as a tableView section header:
func sortByDate() { let datesInSessions = sessions.reduce(into: Set<Date>()) { result, sessions in let dateInSession = Calendar.current.startOfDay(for: sessions.dateModel!) result.insert(dateInSession) } for dateInSession in datesInSessions { let dateComp = Calendar.current.dateComponents([.year, .month, .day], from: dateInSession) var sortedContent: [Session] = [] sessions.forEach { sessions in let contComp = Calendar.current.dateComponents([.year, .month, .day], from: sessions.dateModel!) if contComp == dateComp { sortedContent.append(sessions) } } let newSection = Section(sectionDate: dateInSession, sessions: sortedContent) sections.append(newSection) } }
The problem is that whenever I add a new cell (with the same date as the previous cell), the section with the exact same date creates all over again (see the picture).
How do I fix this?
2
Answers
Thanks to an outside help from @OlzhasAkhmetov from MobiDev I was able to fix the repetition of sections and cells.
The sortByDate() function required sections.removeAll() in the very beginning. The final working code of the sortByDate() is as follows:
In this code :
As you do not reset the sections array or update the section contains the sessions you always add a new element in the sections array. So number of sections always get +1 and filled with previous sessions + last one. This will lead to appending a new section in your table view each time you add one new session.