Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is scrolling performance poor for custom table view cells having UISegmentedControl objects?

I have a UITableView with custom cells that were defined in the xib file, and am experiencing poor scrolling performance (choppy) on my device when the cells have a UISegmentedControl on them. NSLog statements reveal that the cells are being allocated and reused as they ought. My code for cellForRowAtIndexPath method is below. Connections are made in the xib as per Apple's documentation. (Scrolls smoothly in simulator btw)

- (UITableViewCell *)tableView:(UITableView *)tableView
              cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell =  
           [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) 
    {
        [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" 
                               owner:self  
                               options:nil];  
        cell = self.tvCell;
        self.tvCell = nil;
    }

    cell.layer.shouldRasterize = YES;     // build error is here

    UILabel *lbl = (UILabel *)[cell viewWithTag:1];

    [lbl setText:[NSString stringWithFormat:@"Q%i", indexPath.row+1]];  

    return cell;
}
like image 741
Alyoshak Avatar asked Jul 14 '10 16:07

Alyoshak


1 Answers

Any drawing that a table cell has to do while it's being scrolled is going to cause performance issues; when you have a lot of subviews, there tends to be a lot of drawing going on, and that will—as you've observed—make your scrolling pretty choppy. There are a couple of ways to try to reduce that.

The first step is to make sure that your cells themselves, and as many of their subviews as possible, have their opaque properties set to YES. Opaque views don't have to get blended with the content underneath them, and that saves a lot of time.

You may also want to set your cells' layers to rasterize themselves, like this:

cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

This will collapse your view hierarchy into one flat bitmap, which is the kind of thing Core Animation just loves to draw. Note that any animating views—activity indicators, for instance—will force that bitmap to be updated every time they change, i.e. a lot. In that case, you won't want the cell to rasterize everything; you might just use a subview with all of your relatively static views (e.g. labels) beneath another subview with any such dynamic content, and only have the first of those rasterized.

like image 153
Noah Witherspoon Avatar answered Jan 02 '23 21:01

Noah Witherspoon