所有 UITableCells 在 UITableView 中滚动和触摸时消失。一切都以编程方式完成,我使用标准的 UITableViewCell 类。
我在某处读到包含我的单元格数据的数组可能被清空,因此 View 无法在滚动时加载数据。但是,我不知道如何验证这一点。
这是我的 TableView 委托(delegate)和数据源:
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)
}
}
在我的 ViewController 的 ViewDidLoad 方法中,我正在执行以下操作:
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)
bên cạnh đó
upcomingLessonsTableViewData.addLessons(upcomingEvents, tableView: upcomingLessonsTableView)
TRONG upcomingEvents
是一个数组。
新发现。当设置一个连续打印出我的类(class)数组内容的计时器时,单元格不会消失。为什么?没有线索。
使下面的变量成为全局变量。让 comcomingLessonsTableViewData;
Tôi là một lập trình viên xuất sắc, rất giỏi!