Johan Sørensen

A scrollview in a tableview cell, properly

Looking at what search terms people use to find this site I see that my article on embedding a UIScrollView inside a UITableViewCell is among the ones that gets the most hits. Which is a shame since that approach is a terrible way of solving it these days.

After iOS 2.1 (or iPhoneOS as it was called back then) or thereabout that terrible responder chain hack is no longer needed, all you need to do is add the scrollview as a subview of the cell and you’re good to go:


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"ScrollCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        UIScrollView *scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 25, 320, 25)];
        scroller.showsHorizontalScrollIndicator = NO;

        UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320*4, 25)];
        contentLabel.backgroundColor = [UIColor blackColor];
        contentLabel.textColor = [UIColor whiteColor];
        NSMutableString *str = [[NSMutableString alloc] init];
        for (NSUInteger i = 0; i < 100; i++) { [str appendFormat:@"%i ", i]; }
        contentLabel.text = str;

        [scroller addSubview:contentLabel];
        scroller.contentSize = contentLabel.frame.size;
        [cell addSubview:scroller];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"cell #%i", indexPath.row];

    return cell;
}

Nothing fancy going on here, just creating a scrollview, add a wider subview, set the contentSize of the scrollview and add it to the UITableViewCells view hierarchy.
I usually prefer to use a UITableView subclass instead of setting up cell view hierarchies in the view controller, but you wouldn’t just copy-paste example code without thinking now would you?