“尝试删除第1部分中的行,但更新前只有1个部分”

我正在尝试删除不符合for循环条件的行。 但是,我得到的错误是:’尝试从第1部分删除第0行,但在更新之前只有1个部分。“我以前从未见过这个,也不确定为什么我会得到它。

我的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = theTableView.dequeueReusableCellWithIdentifier("MyCell") as! TableViewCell cell.titleLabel.text = titles[indexPath.row] cell.priceLabel.text = prices[indexPath.row] cell.descLabel.text = descs[indexPath.row] cell.itemImage.image = itemImages[indexPath.row] cell.userNumber = phoneNumbers[indexPath.row] as! String cell.timeLabel.text = datesHours[indexPath.row]! + "hr" cell.distanceLabel.text = String(locations[indexPath.row]!) + "mi" cell.viewController = self self.theTableView.beginUpdates() for (index, number) in self.locations { if number <= 5 { let indexPath = NSIndexPath(forRow: number, inSection: 1) self.theTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } self.theTableView.endUpdates() 

看起来你正在告诉表格会有比实际想要显示的行更多的行,然后在事后删除它们。

相反,您应该检查数组中的元素是否满足numberOfRowsInSection中(或之前)的条件,并将它们放入实际显示的不同数组中,以便表知道实际显示的行数。 然后在cellForRowAtIndexPath使用新创建的数组,该数组具有实际显示的数据。

 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. self.displayArray = [] for (index, number) in self.locations { if number <= 5 { self.displayArray.Add(self.locations[index]) } } return self.displayArray.Count } 

我假设您的错误与您尝试在首次尝试创建它的方法中更新表有关。 您正在尝试更新尚未完全创建的内容。