我正在尝试动态地将行添加到我的表视图的底部,同时用户正在滚动。这个想法是用户没有注意到这一点,并且可以滚动“无尽”。
当用户到达桌子的底部40个单元格时,我想在底部绘制100个新单元格。
现在我打电话
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
tableView.endUpdates()
应用程序似乎在tableView.endUpdates()
上崩溃了:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds [0 .. 9]'
我坚信在执行更新之前,我UITableView
的dataProvider已正确更新。我不知道为什么会崩溃。
我为此目的做了一个非常直接的实现。任何人都明白为什么下面会崩溃?
private let CellTreshold: Int = 100
var cellCount: Int = 100
@IBOutlet weak var tableView: UITableView!
// UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as! UITableViewCell
cell.index = indexPath.row
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == cellCount - 40 {
print("indexPath = \(indexPath.row); inserting \(CellTreshold) cells")
var indexPaths = [NSIndexPath]()
let beginIndex = cellCount
let endIndex = cellCount + CellTreshold
for i in beginIndex ..< endIndex {
indexPaths.append(NSIndexPath(forRow: i, inSection: 0))
}
cellCount += CellTreshold
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
tableView.endUpdates()
}
}
答案 0 :(得分:0)
我遇到了同样的问题 - 它崩溃了,因为代码在willDisplayCell中。感谢@ A-live的评论
在scrollViewDidScroll中移动我的代码之后,它的工作正常,类似:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeght = scrollView.contentSize.height
let scrollViewHeight = scrollView.frame.size.height
if (contentHeght - offsetY) < 3*scrollViewHeight {
//we are less than 3 page screens from the bottom
let rowNumbers = self.dataModel.getVisibleCells()
let newRowNumbers = self.dataModel.getMoreCells()
let newCells = newRowNumbers - rowNumbers
if newCells > 0 {
debugPrint("ae.ui adding cells \(newCells)")
let rowInd = rowNumbers - 1
var indexPaths = [IndexPath]()
for i in 1...newCells {
indexPaths.append(IndexPath(row: rowInd+i, section: 0))
}
self.beginUpdates()
self.insertRows(at: indexPaths, with: .none)
self.endUpdates()
}
}
}