views:

21

answers:

1

Hi, i am using the code below to implement a volume view into a cell.

[[cell detailTextLabel] setText: @""];
  MPVolumeView *systemVolumeSlider = [[MPVolumeView alloc] initWithFrame: CGRectMake(100, 10, 200, 100)];
  [cell addSubview: systemVolumeSlider];
  [self.view addSubview:cell];
  [systemVolumeSlider release];
  //[MPVolumeView release];

However I have a problem with it. Whenever i scroll up or down in the tableview the MPVolumeView will be added to some other cells aswell. How could I fix this?


A: 

As mentioned in the comments, the cell with the Volume control may get re-used for non-Volume cells so it needs to be removed if it already exists. An example of how this can be done:

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }

    //remove the volume control (which we tagged as 10) if it already exists...
    UIView *v = [cell.contentView viewWithTag:10];
    [v removeFromSuperview];

    cell.textLabel.text = @"some text";

     if (indexPath.section == 7) 
     { 
        if (indexPath.row == 1) 
        { 
            cell.detailTextLabel.text = @""; 
            MPVolumeView *systemVolumeSlider = [[MPVolumeView alloc] initWithFrame:CGRectMake(100, 10, 200, 100)];
            //set a tag so we can easily find it (to remove it)...
            systemVolumeSlider.tag = 10;  
            [cell.contentView addSubview:systemVolumeSlider]; 
            [systemVolumeSlider release]; 
            return cell; 
        }
     }

    cell.detailTextLabel.text = @"detail";

    return cell;
}

In your comments, it seems the volume control should only be on the 2nd row of the 8th section so the example is written that way. Modify as needed.

aBitObvious