Search code examples
iphoneiosxcodeuitableviewuislider

Slider gets reload in Table View in Iphone SDK


In my app, i add a slider in Table view i.e. each row contains a slider & It also works fine.

But when i scroll the table view the slider get reload i.e. each shows me starting position rather than slider value.

//My code is as follow for slider in table cell:

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

     NSString *CellIdentifier=[NSString stringWithFormat:@"CellIdentifier%d",indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];

        return cell;
    }


    UISlider*  theSlider =  [[[UISlider alloc] initWithFrame:CGRectMake(174,12,120,23)] autorelease];
        theSlider.maximumValue=99;
        theSlider.minimumValue=0;
        [cell addSubview:theSlider];

return cell;
}

How can i solve this??


Solution

  • - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
     NSString *CellIdentifier=[NSString stringWithFormat:@"CellIdentifier%d",indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
    
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; UISlider*  theSlider =  [[[UISlider alloc] initWithFrame:CGRectMake(174,12,120,23)] autorelease];
        theSlider.maximumValue=99;
        theSlider.minimumValue=0;
        [cell addSubview:theSlider];
    }  return cell;
    

    This way the slider gets created only when cell is nil i.e cell gets created. and use tableView:willDisplayCell:forRowAtIndexPath: method to set the slider value like slider.value = yourvalue;