将额外的行添加到由NSFetchedResultsControllerpipe理的UITableView
我在我的应用程序中使用UITableViewController
作为表,并且我添加了一个NSFetchedResultsController
来提供数据在表中显示(设置self
为委托)。
不过,我想添加一个唯一的单元格作为表的最后一个单元格,与NSFetchedResultsController
谓词产生的项目无关,我希望这个单元格始终位于表格的底部。
我已经尝试在表视图数据源中简单地添加1到这些方法:
- (NSUInteger)numberOfSectionsInTableView:(UITableView *)sender { return [[self.fetchedResultsController sections] count] + 1; } - (NSUInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSUInteger)section { return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects] + 1; }
然后捕捉这样的额外行的情况下(表只有1节):
- (UITableViewCell *)tableView:(UITableView *)sender cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == [self.fetchedResultsController.fetchedObjects count]) { //Generate the last cell in table. } else { //Generate the rest of the cells like normal. } return nil; //To keep the compiler happy. }
这将检查索引是否是最后一个单元格并进行适当的处理。
但是,我仍然在运行时收到以下错误:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
任何想法是什么造成这个? 还是有一个更好的方式添加一个额外的行到由NSFetchedResultsController控制的表视图?
如果您按照文档(更新等)中的说明实现所有数据源方法,那么获取的结果控制器与tableview紧密相连。 它会变得相当混乱和哈克。
你的“额外的行”可以是表的页脚视图吗? 这将永远在底部。 使它看起来像一个细胞并不是太多的工作,但从它的外观来看,你希望它看起来不同于其他细胞。
鉴于表只有一个部分,这段代码看起来是错误的:
- (NSUInteger)numberOfSectionsInTableView:(UITableView *)sender { return [[self.fetchedResultsController sections] count] + 1; }
我怀疑当桌面视图试图检索第二部分时出现崩溃; + 1应该被删除。
使用来自提取结果控制器的表可以做更复杂的事情(请参阅NSFetchedResultsController预先logging一行或一节 ),所以我确信这个简单的例子可以工作。
为什么不使用内置的UITableView的页眉和页脚视图?
例:
UIView *customBottomView = [UIView alloc] init... //set up your View (what you called custom bottom cell
)
self.table.tableFooterView = customBottomView; //或者tableHeaderView
从技术上讲,你正在添加一个视图,该视图显示在被添加到表中并被TableView奇妙处理的表的下面(或上面)。 对于用户来说,无法确定这是(最后一个)单元格还是视图。 如果您打算使用didSelectRowAtIndexPath之类的方法,只需要解决