我试图在 TableView 中显示 2 种不同类型的数据。 videoNews 数组只有一个要显示在 indexPath.row == 1 中的元素,而 Suggested News 数组有许多要显示在 indexPath.row >= 4中的元素强>.介于两者之间的一切都只是标签,照原样进行。当显示来自 SuggestedNews 数组的元素时,问题就出现了,tableView 给出了 index out of range 错误,即使数组有元素并且 numberOfRowsInSection 也获得了正确数量的元素。
TableView代码
var SuggestedNews = [VideoNews]()
var videoNews = [VideoNews]()
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (5 + SuggestedNews.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoArticleCell", for: indexPath) as? VideoArticleCell {
let video = self.videoNews[indexPath.row]
cell.updateUI(video: video)
return cell
}
} else if indexPath.row == 1 {
if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoFirstLabelCell") {
return cell
}
} else if indexPath.row == 2 {
if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoSubmissionCell", for: indexPath) as? VideoSubmissionCell {
return cell
}
} else if indexPath.row == 3 {
if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoSecondLabelCell") {
return cell
}
} else if indexPath.row >= 4 {
if let cell = tableView.dequeueReusableCell(withIdentifier: "VideoSuggestionCell", for: indexPath) as? VideoSuggestionCell {
let latest = self.SuggestedNews[indexPath.row] //Index out of range
cell.updateUI(latest: latest)
return cell
}
}
return UITableViewCell()
}
最佳答案
如果 index.row == 4 你的代码在这一行,但你想显示数组的第一个元素;因此,您的第一个数组索引等于 0。
let latest = self.SuggestedNews[indexPath.row - 4]
如果您有 4 个单元格与 SuggestedNews 不同,则您的返回不是 return (5 + SuggestedNews.count)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (4 + SuggestedNews.count)
}
关于ios - tableView 中的索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182589/