mnort9
mnort9

Reputation: 1820

Reuse of table cells issue

I believe I am incorrectly implementing cellForRowAtIndexPath. I have a UISlider that is hidden by default and appears when a button is pressed in the table cell. When I press the button in the first cell,the slider appears not only in the first cell, but in every third cell when I scroll down. I am currently avoiding this by reseting the slider's hidden property to YES in cellForRowAtIndexPath. I also do this for other views in the cell I need hidden by default. This creates a new issue when I scroll back up to the first cell, the slider is hidden because the property is reset in cellForRowAtIndexPath. This leads me to believe I'm doing something wrong.

Here is my code:

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

static NSString *CellIdentifier = @"Cell";

SongsCustomCell *songCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (songCell == nil) {
    songCell = [[SongsCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    NSLog(@"new cell created");
}

NSDictionary *dictionary = [parseTrackArray objectAtIndex: indexPath.row];
NSString *trackTitle = [dictionary objectForKey:@"trackTitle"];
NSString *trackLink = [dictionary objectForKey:@"trackStreamLink"];
songCell.trackLinkString = trackLink;
songCell.trackTitleString = trackTitle;
[songCell.trackTitleLabel setFont:[UIFont fontWithName:@"Calibri" size:22]];
songCell.trackTitleLabel.text = [NSString stringWithFormat:@"%@", trackTitle];

songCell.playButton.hidden = NO;
songCell.playbackSlider.hidden = YES;
songCell.playerHasLoaded = NO;
songCell.moviePlayer.view.hidden = YES;

return songCell;
}

Upvotes: 0

Views: 1743

Answers (2)

iTukker
iTukker

Reputation: 2083

Your problem is that your cells are being reused when you are scrolling down. So when your slider is visible for a cell thats is scrolling out of view, that cell will be reused and thus the slider is still visible.

To avoid this implement prepareForReuse in your custom cell to reset your slider as soon as your cell is being reused.

Next to that you still need to store the state of the slider in your model, so you are able to restore that state once that object is coming back in view.

Nevertjeless its a good practice to set the default state of your custom cell in prepareForReuse

Upvotes: 1

jrturton
jrturton

Reputation: 119242

You need to store the hidden / unhidden status of your slider in your data model somewhere, and then set the slider's visibility appropriately from that in cellForRowAtIndexPath. If only one slider is visible at once, you can store the index path as an ivar in your view controller, if not then you will need to have another key in your dictionary holding an NSNumber bool or something.

Upvotes: 3

Related Questions