Daniel Wallman
Daniel Wallman

Reputation: 418

UIScrollView in UITableView content problems

I have a scrollview inside each cell in my tableview, although the pictures embed in my scrollview don't show up until i scroll the tableview up and down... I have a custom class with a @property for the scrollview and the cell. I have my code for setting the scrollview in the cellForRowAtIndexPath: method. This should be called upon initial creation of the cells as well? Im confused.

How can I get rid of the problem and make the images appear at first when I start the app?

Related code:

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

    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    for (int i = 0; i < [imageArray count]; i++) {
        CGRect frame;
        frame.origin.x = cell.scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = cell.scrollView.frame.size;

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = [UIImage imageNamed:[imageArray objectAtIndex:i]];
        [cell.scrollView addSubview:imageView];
    }

    cell.scrollView.contentSize = CGSizeMake(cell.scrollView.frame.size.width * [imageArray count], cell.scrollView.frame.size.height);

    return cell;
}

Upvotes: 0

Views: 563

Answers (1)

Hermann Klecker
Hermann Klecker

Reputation: 14068

This is not exactly related to your question but you will run into this issue too:

Don't forget that your cells will be reused. Upon reusage (lets say the user scrolls down, a cell is moved upwards off the screen and the next that appears on the bottom will be physically the instance of CustomCell that just disappeard and was reused.)

Therefore add:

   for (UIView *aView in [NSArray arrayWithArray:cell.subviews]) {
       [aView removeFromSuperview];
       // if you don't arc then release them and take care of their subviews - if any. 
   }

before adding any new UIImageView. (I thought there was a method for removing all subviews in one go but did not find it)

Upvotes: 1

Related Questions