【问题标题】:How to display a label when tableView is emptytableView为空时如何显示标签
【发布时间】:2015-04-11 08:34:33
【问题描述】:

我想在 tableView 为空时显示一个标签。 我尝试了此页面上提出的其他解决方案,但没有一个对我有用。我想说“按添加按钮创建一个新课程”之类的话。我的 TableviewController 是:

#import "ClasesTableViewController.h"
#import "ClasesTableViewCell.h"
#import "ViewController.h"

@interface ClasesTableViewController ()

@end

@implementation ClasesTableViewController

@synthesize clases;

- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context  = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navigationItem setTitle:@"Clases"]; /*Cambia el titulo del navigation controller*/

    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}]; /*Cambia el color de las letras del navigation controller bar del menu principal*/

    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:62/255.0f green:152/255.0f blue:73/255.0f alpha:1.0f]];

    self.TableView.tableFooterView = [[UIView alloc] init]; /*Esta linea hace que en la tabla solo aparezcan el numero de filas que tienes establecidas, es decir, que las vacias no aparezcan*/

    self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; /*Cambia el color del boton de la izquierda*/

    UIBarButtonItem *infoBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"info_white48@2x.png"] style:UIBarButtonItemStylePlain target:self  action:@selector(infoAction)];

    self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects: _AddBarButton, infoBarButtonItem, nil];


}


-(void)infoAction
{
    NSInteger clasesDadas = clases.count;

    NSString *inStr = [NSString stringWithFormat:@"\nClases dadas: %d", (int)clasesDadas];


    UIAlertView *alertatiempo = [[UIAlertView alloc] initWithTitle:@"Información" message:inStr delegate:self cancelButtonTitle:@"Aceptar" otherButtonTitles:nil];
    [alertatiempo show];

}



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"UpdateClase"]) {
        NSManagedObject *selectedClase = [clases objectAtIndex:[[self.TableView indexPathForSelectedRow] row]];
        ClasesViewController *destViewController = segue.destinationViewController;
        destViewController.clase = selectedClase;
        destViewController.numberOfClasses = clases.count;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Clases"];
    clases = [[moc executeFetchRequest:fetchRequest error:nil] mutableCopy];

    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return clases.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    /*UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];*/
    ClasesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


    //Configure the cell
    NSManagedObject *clase = [clases objectAtIndex:indexPath.row];
    [cell.dateLabel setText:[NSString stringWithFormat:@"%@", /*countString,*/ [clase valueForKey:@"date"]/*, [clase valueForKey:@"date"]*/]];
    [cell.timeLabel setText:[clase valueForKey:@"time"]];
    [cell.paidLabel setText:[clase valueForKey:@"paid"]];
    cell.paidImage.image = [UIImage imageNamed:@" "];

    if ([cell.paidLabel.text isEqualToString:@"No"] || [cell.paidLabel.text isEqualToString:@"no"]) {
        cell.paidLabel.textColor = [UIColor redColor];
    }
    if ([cell.paidLabel.text isEqualToString:@"Si"] || [cell.paidLabel.text isEqualToString:@"si"]) {
        cell.paidLabel.textColor = [UIColor greenColor];
        cell.paidImage.image =[UIImage imageNamed:@"paid_green@2x.png"];
    }

    return cell;

}



 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

     // Return NO if you do not want the specified item to be editable.
     return YES;

 }


 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

     NSManagedObjectContext *context = [self managedObjectContext];

     if (editingStyle == UITableViewCellEditingStyleDelete) {
         // Delete the row from the data source
         [context deleteObject:[clases objectAtIndex:indexPath.row]];

         //invoke the "save" method to commit the change
         NSError *error = nil;
         if (![context save:&error]) {
              NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
             return;
         }

         //Remove clase from table view
         [clases removeObjectAtIndex:indexPath.row];
         [self.TableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

     }
 }

@end

谁能帮帮我?非常感谢。

【问题讨论】:

  • 解释你尝试过的最接近的地方以及它做错了什么

标签: ios uitableview uilabel


【解决方案1】:

一个简单的解决方案是使用其他自定义 UITableViewCell 来显示空状态。

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
{
    return clases.count>0?clases.count:1;  //Return 1 if clases array is empty 
}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
  if(clases.count==0 && indexPath.row == 0)
  {
    //return a custom cell  with the label "Press the add button to create a new class"
  }
  else
  {
    //return an instance of ClasesTableViewCell as you was doing in your code which represents one class
  }
}

【讨论】:

    【解决方案2】:

    实际上有一个很棒的库,叫做DNZEmptyDataSet,它基本上是免费的。

    您需要做的就是将您的表格视图控制器分配为空数据集的委托和数据源:

    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    

    然后只返回您想在

    中显示的任何消息
    - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView; 
    

    还有很多附加功能,请查看他们的 Github 网页以获取更多文档。它们还允许您显示图像、字幕、按钮、完全自定义的视图等。

    请记住将自己从dealloc 方法中的委托/数据源中删除!

    【讨论】:

      【解决方案3】:

      我使用的另一个解决方案是检查单元格是否没有结果,使用索引路径 1(或 2)处的 uitableview 单元格来显示消息。

      在 cellforrowatindexpath 中: 如果没有结果 如果 indexpath.row 等于 2 Cell.titlelable.text 等于“按+按钮”

      这对我来说是最简单的方法,但您也可以像下面其他成员所说的那样使用自定义单元格。

      希望对你有帮助。

      【讨论】:

        【解决方案4】:

        制作 UILabel 并根据需要提供文本以及在哪里获得 Web 服务响应,然后检查是否有要显示的数据,然后制作 tableview.backgroundView = nil 否则将标签作为 backgroundView 所以 tableview.backgroundView = yourLabel

        您可以根据需要设置任何视图。也可以放置按钮。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-19
          • 1970-01-01
          相关资源
          最近更新 更多