【问题标题】:IOS/Objective-C: Display message in background view of tableview when no resultsIOS/Objective-C:无结果时在tableview的背景视图中显示消息
【发布时间】:2018-09-04 01:39:54
【问题描述】:

当获取的结果控制器未返回任何行 as here 时,我正在尝试显示未找到结果的消息。

为此,我将代码放入 numberOfRows 方法中。但是,它正在引发异常。这是我的代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

      if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];

    } else {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];

        int numRows =[sectionInfo numberOfObjects];
        if (numRows>=1) {

             return [sectionInfo numberOfObjects];
        }
        else {

            UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];

            messageLabel.text = @"No comments yet.";
            messageLabel.textColor = [UIColor grayColor];
            messageLabel.numberOfLines = 0;


            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

            return 0;
        }
}

我应该把这段代码放在别处吗?或者它可能有什么问题会导致它抛出异常。

提前感谢您的任何建议。

【问题讨论】:

  • numberOfRowsInSection(和其他数据源方法)可以被调用很多很多次。您不应该在该方法中加载数据。您不应该使用该方法创建和添加视图。
  • 什么异常?创建数据源后尝试处理它。
  • @rmaddy,类似于在 viewdidload 中检查 [fetchedResultsController.fetchedObjects count]?
  • @user6631314 确保标签始终在 UITableView 的背景视图中。知道有多少结果后,立即将其设置为隐藏或不隐藏。这可能是在此方法之外的其他地方。
  • 好的。除了切换隐藏到 viewdidload 之外,我将所有内容都移动了。现在我只需要在获取结果后为标签显示 hidden=NO 即可。您能否建议一个在表加载后触发的除委托之外的方法(具有 nsfetchedresultscontroller 的结果)?当我将代码放入viewwillappear时,它仍然显示results==0;

标签: ios objective-c tableview


【解决方案1】:

使用节数方法而不是节中的行数。 像这样。

if self.yourArray.count > 0 {
    return 1
} else {
   //Your Empty Message
   return 0
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多