【问题标题】:iOS - Add a cell to empty UITableView Section w/ Core Data and NSFetchedResultsControlleriOS - 将单元格添加到带有核心数据和 NSFetchedResultsController 的空 UITableView 部分
【发布时间】:2012-07-20 17:39:54
【问题描述】:

我正在使用 Core Data 和 NSFetchedResults 控制器在我的应用程序中填充 UITableViewCell(普通样式)。 TableView 有 3 个部分,每个部分都有一个 viewForHeaderInSection 和一个 viewForFooterInSection。用户将输入将放在每个部分中的项目。

当其中一个部分没有项目时,它会完全消失。我想知道是否有可能做到这一点,所以如果一个部分是空的,它会显示一个新的单元格,上面写着“没有条目”或类似的东西(可能是 UIImageView 或其他视图?),然后如果该部分中有新项目,则消失。

有谁知道如何做到这一点?

这是我的数据源的代码。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{    
   return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[[self.fetchedResultsController sections] objectAtIndex:section] name];
}

此外,该部分本身在没有行时会从 TableView 中删除,那么我怎样才能将“无条目”单元格添加到正确的部分?

【问题讨论】:

    标签: ios objective-c uitableview sections


    【解决方案1】:

    如果该部分未出现在表格视图中,则它不会从获取结果中返回,尽管您说您有 3 个部分。 您可以通过以下方式手动返回:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 3;
    }
    

    然后

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {    
       if  ([[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects] == 0){     
           return 1;
       } else {
           return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
       }
    }
    

    在您的 cellForRowAtIndexPath: 测试中是否为空..

    if ([[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects] == 0){
    cell.textLabel = @"No Entries";
    

    }

    只是一个想法。

    编辑:请注意,如果您尝试捕获未通过 fetch 返回的索引,您的应用可能会崩溃。

    【讨论】:

    • 当我将 numberOfSectionsInTableView 设置为 3 时,我在启动时遇到了崩溃。有什么想法吗?
    • 是的,您的提取结果没有返回 3 个部分。然后你尝试访问一个空数据......然后bam,崩溃。看看你的核心数据,并尝试相应地处理你的数据......你想要有 3 个部分......但你没有这些数据。我相信你的崩溃就在这里:[[[self.fetchedResultsController section] objectAtIndex:section]
    【解决方案2】:

    您需要修改 numberOfRowsInSection 函数以检查该部分是否没有真正的行,如果是,则返回 1(而不是 0)。

    然后,在cellForRowAtIndexPath 中,检查您是否有该部分的数据,当您发现没有时,只需创建“无条目”单元格。

    【讨论】:

      猜你喜欢
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      相关资源
      最近更新 更多