В моем приложении у меня есть TabBar
навигационная система. Когда приложение загружает контроллер представления для первой вкладки, calendarTableView
в нем загружается нормально, но если я переключаюсь на другую вкладку, а затем возвращаюсь к первой, я получаю ошибку NSInternalInconsistencyException Attempted to dequeue multiple cells for the same index path
. Объявление ячейки как: let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell
дает мне ошибку. Пока что я решил эту проблему, как советовали в других статьях, не указав indexPath в объявлении ячейки в методе cellForRowAt
и объявив его как: let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell
, но означает ли это, что я неправильно управляю источником данных или в чем причина? иметь эту ошибку? Не следует указывать indexPath
всегда? Я сделал тест, поскольку у меня не было проблемы до сих пор, и я изменил системную дату на более раннюю дату, скажем, 10-го числа месяца, и я не получаю ошибку. Значит ли это, что просмотр таблицы пытается снять слишком много ячеек? Ты видишь, что происходит? Я был бы очень признателен за объяснение этого.
Как всегда, большое спасибо за ваше время.
Вот код, который я использую:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell", for: indexPath) as! CalendarTableViewCell
// let cell = tableView.dequeueReusableCell(withIdentifier: "calendarCell") as! CalendarTableViewCell
cell.configureUi()
let date = datesArray[indexPath.row]
cell.cellDate = String( describing: date)
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .weekday], from: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let dayInWeek = dateFormatter.string(from: date)
// cell.dayLabel.text = "\(String(describing: components.day!))" + " " + "\(dayNamesArray[components.weekday! - 1])"
cell.dayLabel.text = "\(String(describing: components.day!))" + " " + dayInWeek
cell.cellWeekday = components.weekday!
// print("cell weekday is: \(cell.cellWeekday!)") // prints correct weekday
cell.cellId = "\(String(format:"%04d", components.year!))" + "\(String(format:"%02d", components.month!))" + "\(String(format:"%02d", components.day!))"
self.selectedDate = cell.cellId // used for time slots cellId
// print("##################### selectedDate in tableview is :\(self.selectedDate) ")
// highlighting current day cell
if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
cell.layer.borderWidth = 4
if Theme.selectedTheme == 1 {
if #available(iOS 11.0, *) {
cell.layer.borderColor = Theme.calendarCellToday?.cgColor
} else {
// Fallback on earlier versions
cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
}
} else if Theme.selectedTheme == 2 {
if #available(iOS 11.0, *) {
cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
} else {
// Fallback on earlier versions
cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
}
}
// print(" @@@@@@@@@@@@@@@@@@@@@@@@@@ selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
self.selectedDate = cell.cellId
}
return cell
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
cell.configureUi()
// highlighting current day cell
if indexPath.row == self.actualDay - 1 && self.actualMonth == self.displayedMonth {
cell.layer.borderWidth = 4
if Theme.selectedTheme == 1 {
if #available(iOS 11.0, *) {
cell.layer.borderColor = Theme.calendarCellToday?.cgColor
} else {
// Fallback on earlier versions
cell.layer.borderColor = Theme.calendarCellTodayRgb.cgColor
}
} else if Theme.selectedTheme == 2 {
if #available(iOS 11.0, *) {
cell.layer.borderColor = Theme.calendarCellToday2?.cgColor
} else {
// Fallback on earlier versions
cell.layer.borderColor = Theme.calendarCellTodayRgb2.cgColor
}
}
// print(" @@@@@@@@@@@@@@@@@@@@@@@@@@ selected cell weekday is: \(cell.cellWeekday!) @@@@@@@@@@@@@@@@@@@@ ")
self.selectedDate = cell.cellId
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? CalendarTableViewCell {
cell.layer.borderWidth = 4
if Theme.selectedTheme == 1 {
if #available(iOS 11.0, *) {
cell.layer.borderColor = Theme.firstTintColor?.cgColor
} else {
// Fallback on earlier versions
cell.layer.borderColor = Theme.firstTintColorRgb.cgColor
}
} else if Theme.selectedTheme == 2 {
if #available(iOS 11.0, *) {
cell.layer.borderColor = Theme.firstTintColor2?.cgColor
} else {
// Fallback on earlier versions
cell.layer.borderColor = Theme.firstTintColorRgb2.cgColor
}
}
self.updateTimeSlots(selectedCell: cell)
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
let cell: CalendarTableViewCell = tableView(self.calendarTableview, cellForRowAt: IndexPath.init(row: self.actualDay - 1, section: 0)) as! CalendarTableViewCell
self.updateTimeSlots(selectedCell: cell)
}