1.我有两个结构体用于传递给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)
}
}
1.数据从另一个viewController通过展开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()
}
1.我有一个函数来设置日期作为tableView节的标题:
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)
}
}
**问题是,每当我添加一个新单元格(与前一个单元格具有相同的日期)时,具有完全相同日期的部分就会重新创建(见图片)。
我该怎么解决?
2条答案
按热度按时间oxcyiej71#
在此代码中:
由于您没有重置节数组或更新包含会话的节,因此始终在节数组中添加新元素。因此,部分的数量始终为+1,并填充以前的会话+最后一个。这将导致每次添加一个新会话时在表视图中追加一个新节。
vuv7lop32#
感谢MobiDev的@OlzhasAkhmetov的外部帮助,我能够修复部分和单元格的重复。
sortByDate()函数一开始就需要section.removeAll()。sortByDate()的最终工作代码如下: