我试图在表格视图中显示2种不同类型的数据。 videoNews数组只有一个要在 indexPath.row == 1 中显示的元素,而推荐的新闻数组有许多要在 indexPath.row&gt; = 4 <中显示的元素/ strong>即可。介于两者之间的所有东西都只是标签而且一如既往。当来自SuggestedNews数组的元素显示tableView给出索引超出范围错误时,问题就出现了,即使数组中有元素且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()
}
答案 0 :(得分:3)
如果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)
}