Reputation: 483
All UITableCells disappear on scroll and touch in the UITableView. Everything is done programmatically and I use the standard UITableViewCell class.
I read somewhere that the array containing my cell data may be emptied and the view can therefore not load the data on scroll. However, I don't know how to verify this.
Here is my TableView delegate and DataSource:
class LessonTable: NSObject, UITableViewDataSource, UITableViewDelegate {
private var lessons = [LessonItem]()
public var backgroundColor = UIColor(white: 0.97, alpha: 1)
func addLessons(_ lessons: [LessonItem], tableView: UITableView){
tableView.beginUpdates()
//Construct array of indexPaths
var indexPaths = [IndexPath]()
for i in 0...lessons.count {
indexPaths.append(IndexPath(row: lessons.count - 1 + i, section: 0))
}
//Append all lessons to Lessons array
self.lessons.append(contentsOf: lessons)
//Insert rows
tableView.insertRows(at: indexPaths, with: .automatic)
tableView.endUpdates()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lessons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "lessonCell", for: indexPath)
cell.backgroundColor = backgroundColor
let row = indexPath.row
cell.textLabel?.text = lessons[row].Title
cell.detailTextLabel?.text = lessons[row].Start.Formatted() + " - " + lessons[row].Stop.Formatted()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let row = indexPath.row
print(lessons[row].Title)
}
}
In my ViewController's ViewDidLoad method I'm doing the following:
let upcomingLessonsTableView = UITableView(frame: CGRect(x: 0, y: 100, width: (card.frame.size.width), height: 90))
let upcomingLessonsTableViewData = LessonTable()
upcomingLessonsTableView.dataSource = upcomingLessonsTableViewData
upcomingLessonsTableView.delegate = upcomingLessonsTableViewData
upcomingLessonsTableView.register(UITableViewCell.self, forCellReuseIdentifier: "lessonCell")
upcomingLessonsTableView.backgroundColor = upcomingLessonsTableViewData.BackgroundColor
card.addSubview(upcomingLessonsTableView)
And also
upcomingLessonsTableViewData.addLessons(upcomingEvents, tableView: upcomingLessonsTableView)
where upcomingEvents
is an array.
NEW DISCOVERY. When setting a timer that continuously prints out the contents of my lessons array, the cells doesn't disappear. Why? No clue.
Upvotes: 1
Views: 1429
Reputation: 1389
In your cellForRow
method add this as! LessonCell
your let cell
line
Should be like:
let cell = tableView.dequeueReusableCell(withIdentifier: "lessonCell", for: indexPath) as! LessonCell
Upvotes: 0