【问题标题】:Show label if Table View is empty如果表格视图为空,则显示标签
【发布时间】:2012-02-26 23:26:33
【问题描述】:

我正在使用 Core Data 来存储项目名称并将其显示在表格视图中。当表视图为空(数据库中没有数据)时,它是空白的。从用户的角度来看,这不是很好,所以我希望能够显示一个标签,上面写着“没有项目”。

我该怎么做?我需要:

  1. 检查数据库是否为空并设置一个BOOL
  2. 如果此 BOOL 设置为 true 或 YES,是否显示标签?或将 cell.textLabel.text 设置为“无项目”

如果我走在正确的轨道上,我会非常感谢一些示例代码,让我朝着正确的方向前进。

谢谢

【问题讨论】:

  • 你不接受,发生了什么?
  • 我使用了不同的方法 - 即将发布

标签: objective-c ios uitableview core-data


【解决方案1】:

我最终使用以下代码检查我的核心数据数据库是否为空。工作出色。这必须在 CoreDataController.m 文件中。

NSLog(@"Total number of rows = %d ", totalNumberOfRowsInDatabase);

    if (totalNumberOfRowsInDatabase == 0)
    {

        NSLog(@"Database is empty");
        UIImage *image = [UIImage imageNamed:@"emptyTable.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [imageView setFrame:self.tableView.bounds];
        [self.tableView setBackgroundView:imageView];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.tableView setBackgroundColor:[UIColor clearColor]];

    }
    else 
    {
        [self.tableView setBackgroundView:nil];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [self.tableView setBackgroundColor:[UIColor whiteColor]];
    }

    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];

【讨论】:

    【解决方案2】:
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
       if (section == mySection) return MAX(dataCount, 1);
       else // yadda
    }
    
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
       // yadda
    
       if ([indexPath section] == mySection) {
          if (dataCount == 0) return mySpecialCell;
       }
    
    
       // yadda
    }
    

    【讨论】:

    • mySection 是指您希望此“无项目”行出现的部分。可能是 0。所以 if 语句只是确保您将单元格放在正确的部分。
    • 我的意思是它是一个符号,代表你必须显示的数据记录的数量。如果为零,则您的数据库为空。接下来你会问我mySpecialCell是什么?
    【解决方案3】:

    有一个方便的库:UITableView-NXEmptyView

    简单到:

    tableView.nxEV_emptyView = yourView
    

    UPD:还有更灵活的东西,up-to-date solution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 2011-05-14
      相关资源
      最近更新 更多