【发布时间】:2015-03-09 05:00:23
【问题描述】:
我有两个 UITableView 嵌入到 UIViewController 中。两者都是动态的并且检索不同的数据。问题是在使用- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 时,两个表中都使用了 indexPath。
这里有解决方法吗?我像这样引用我的实体:
//tableView2 has a cell named differently
static NSString *CellIdentifier = @"Cell";
static NSString *CellIdentifier2 = @"Cell2";
//reference the cells to the right tables
UITableViewCell *cell = [self.tableView1 dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath:indexPath];
UITableViewCell *cell2 = [self.tableView2 dequeueReusableCellWithIdentifier: CellIdentifier2 forIndexPath:indexPath];
//create access to details the cell will display from the core date
entity1 * e1 = [self.fetchedResultsController objectAtIndexPath:indexPath];
//this is the issue
//entity2 * e2 = [self.fetchedResultsController2 objectAtIndexPath:indexPath];
提到的问题是 indexPath。如果我尝试使用两个实体来运行应用程序,这两个实体都等于它们各自的 fetchedResults,它会由于 indexPath 被重用而导致错误。如果我创建另一个 indexPath 它会导致此错误(可以理解):
'与 UITableView 一起使用的索引路径无效。传递给表视图的索引路径必须恰好包含两个指定节和行的索引。如果可能,请使用 UITableView.h 中 NSIndexPath 上的类别。'
我的问题是,如何在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法中重用或创建对 NSIndexPath 的单独引用,或者是否有解决方法?
我已经尝试在方法中使用 if/if else 语句,但这会在两个表中显示相同数量的单元格;如果 table1 有 10 行,则 table2 将有 10 行,无论内容如何。
下面的代码可能不正确,我没有足够的经验来实现两个表视图,但这不是主要问题:
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if ([self fetchedResultsController]){
return [[self.fetchedResultsController sections] count];
}
if ([self fetchedResultsController2]) {
return [[self.fetchedResultsController2 sections] count];
}
else{
return 0;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self fetchedResultsController]){
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
if ([self fetchedResultsController2]){
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController2 sections]objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
else{
return 0;
}
}
【问题讨论】:
-
在 cellForRowAtIndexPath 中需要一个 if-else 块,就像在 numberOfRowsInSection 和 numberOfSectionsInTableView 中一样。
-
我知道我忘记在问题中添加一些内容。会更新。可悲的是,这似乎也不起作用。
-
您应该在 cellForRowAtIndexPath 中发布您尝试使用 if-else 块的实际代码。如果你做得好,它应该可以工作。
-
如果您在两个表视图之间共享委托对象,
cellForRowAtIndexPath方法应该根据tableView参数返回适当的结果。您没有显示执行此操作的代码...您显示代码为两个 tableViews 执行某些操作,而不管哪个 tableView 调用该方法。正如你所说,indexPath 只与一个有关。 -
分享您的
cellForRowAtIndexPath代码,然后我们可以识别您的错误
标签: ios objective-c iphone uitableview