swift 3.0 中的索引超出范围错误
Index out of range error in swift 3.0
func loadMoreData(lBound: Int, uBound: Int){
for i in lBound...uBound{
tempArray.append(arrayDealPage[i])
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
self.dealsTable.reloadData()
})
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if arrayDealPage.count != tempArray.count
{
let lastItem = tempArray.count - 1
if indexPath.row == lastItem{
loadMoreData(lBound: tempArray.count, uBound:(tempArray.count-1)+20)
}
}
}
我从图像数组中获取了 195 个数据,我想一次只显示 20 个,然后滚动添加另外 20 个。上面的代码工作正常,但是当我到达大约 181 或 182 个单元格时,它崩溃索引超出范围错误.195 数组计数可以在未来增加如何解决索引超出范围error.Could有人帮助我提前感谢。
您不检查 uBound 索引是否在 arrayDealPage 数组边界之外。
试试这个:
func loadMoreData(lBound: Int, uBound: Int){
// checkeduBound variable never go outside the array bounds
var checkeduBound = uBound
if uBound >= arrayDealPage.count {
checkeduBound = arrayDealPage.count-1
}
//edited
if lBound > checkeduBound { return }
//use new checkeduBound here
for i in lBound...checkeduBound{
tempArray.append(arrayDealPage[i])
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
self.dealsTable.reloadData()
})
}
func loadMoreData(lBound: Int, uBound: Int){
for i in lBound...uBound{
tempArray.append(arrayDealPage[i])
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
self.dealsTable.reloadData()
})
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if arrayDealPage.count != tempArray.count
{
let lastItem = tempArray.count - 1
if indexPath.row == lastItem{
loadMoreData(lBound: tempArray.count, uBound:(tempArray.count-1)+20)
}
}
}
我从图像数组中获取了 195 个数据,我想一次只显示 20 个,然后滚动添加另外 20 个。上面的代码工作正常,但是当我到达大约 181 或 182 个单元格时,它崩溃索引超出范围错误.195 数组计数可以在未来增加如何解决索引超出范围error.Could有人帮助我提前感谢。
您不检查 uBound 索引是否在 arrayDealPage 数组边界之外。 试试这个:
func loadMoreData(lBound: Int, uBound: Int){
// checkeduBound variable never go outside the array bounds
var checkeduBound = uBound
if uBound >= arrayDealPage.count {
checkeduBound = arrayDealPage.count-1
}
//edited
if lBound > checkeduBound { return }
//use new checkeduBound here
for i in lBound...checkeduBound{
tempArray.append(arrayDealPage[i])
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25, execute:{
self.dealsTable.reloadData()
})
}