我有一个超过5个单元格的tableview,但是,由于行的高度,屏幕上只出现了5个单元格。在tableview外面有一个按钮,通过点击它,我想访问每个单元格中的内容。以下是点击代码,
@IBAction func submitTapped(_ sender: Any) {
//array.count is bigger than the number of appearing cells on the screen.
for i in 0..<array.count {
let index = IndexPath(row: i, section: 0)
let cell = self.table.cellForRow(at: index) as! CustomTableViewCell
for a in 0...6 {
print(i)
print(a)
if let letter = cell.letter.text {
print(letter)
}
}
}
}
一旦按下按钮,我得到了代码旁边的错误让cell = self.table.cellForRow(at:index)为! CustomTableViewCell,Thread 1:致命错误:在解包Optional值时意外发现nil
我认为是因为屏幕上出现的单元格的数量,如果array.count等于或小于屏幕上可以出现的单元格数,那么就没有错误。
我调整了单元格的高度并在屏幕上显示了x个单元格,然后如果array.count> x,则崩溃,如果等于或小于x,则它会起作用。
我不确定问题是什么,是因为可重复使用的细胞?如何访问不在屏幕上的单元格中的内容?
Modify your method:
@IBAction func submitTapped(_ sender: Any) {
//array.count is bigger than the number of appearing cells on the screen.
for i in 0..<array.count {
let index = IndexPath(row: i, section: 0)
if let cell = self.table.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as? CustomTableViewCell {
for a in 0...6 {
print(i)
print(a)
if let letter = cell.letter.text {
print(letter)
}
}
}
}
}