我有2个coredata数组。一个包含3个元素,另一个包含3个元素。现在,我想在我的tableview中加载这两个数组。因此,我的表视图中总共有6行。
我已经像这样实现了...
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let totalCount = (customerDetails.count) + (customerDetails2.count)
return totalCount
}
我尝试在
cellForRowAt...
中加载这两个数组的数据 let customers = customerDetails[indexPath.row] //CRASHES HERE
for i in 0..<(customerDetails.count) {
cell.nameLabel.text = customers.fname
if i == customerDetails.count {
break
}
}
let customers2 = customerDetails2[indexPath.row]
for i in 0..<(customerDetails2.count) {
cell.nameLabel.text = customers2.fname
if i == customerDetails2.count {
break
}
}
但是它在提到
Index out of range
的行上崩溃,可能是因为customerDetails
只有3行,而加载的总单元数是6行。在这种情况下可以做什么?
最佳答案
if indexPath.row < customerDetails.count
{
// load from customerDetails array
let customer = customerDetails[indexPath.row]
}
else
{
// load from customerDetails2 array
let customer = customerDetails2[indexPath.row - customerDetails.count]
}