简体   繁体   中英

Redraw a UITableView

I need to literally redraw a UITableView upon an event in my code. But everything I've tryed doesn't seem to work. I've tried [self.tableView reloadData] , I've played with the delegates. The goal I'm trying to achieve is to render a completely different UITableView, with differently formatted cells. So I need to redraw the table. Any help would be appreciated.

Heres my code:

       ...
    if/else...
    }
    //Now I want to reload the tableView
    [tableView reloadData];    //Isn't getting it done
    NSLog(@"index = %i", index);  //Always fires
    tableView.delegate = self;  // Didn't help
    [tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];  // Also nothing
}

The point of what I'm trying to do is this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *CellIdentifier = @"Cell";

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) {
         if (segmentOptions == snacks) {
             cell = [[TableViewCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
              NSLog(@"A");
         } else {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            NSLog(@"B");
         }
     }
  ...
}

You possibly meant something like

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"cell-not-snacks";

    if (segmentOptions == snacks) {
        cellIdentifier = @"cell-snacks";
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
         if (segmentOptions == snacks) {
             cell = [[TableViewCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
         } else {
             cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
         }
     }
}

I think it would be worth looking at the method prepareForReuse in the UITableViewCell Class . This method is invoked just before the object is returned from the UITableView method dequeueReusableCellWithIdentifier:.

You can override this method on your custom UITableViewCell (do not forget including [super prepareForReuse]) in order to redraw whatever you need to redraw.

The problem is: if (cell == nil) { . I removed that and it works perfectly every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM