Reputation: 3289
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??
Upvotes: 0
Views: 826
Reputation: 605
This is really from "cellForRowAtIndexPath
" method . Every time when you are scrolling every cell is getting nil
and reinitialise it. Better you can try with creating custom cell class(BY creating sub class of UITableViewCell
) and also the defining slider in condition "if (cell == nil)
".
Upvotes: 1
Reputation: 1091
- (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;
Upvotes: 3
Reputation: 2980
The problem is that cellForRowAtIndexPath
is called not just once, but every time that the tableView need to render that cell... So you have to be sure that only initialize theSlider
the first time is called...
The best approach is to define a custom UITableViewCell
and put there a property that would store theSlider
, then, when cellForRowAtIndexPath
is called, check if it is already initialized or not, see:
// If the slider is not yet initialized, then do it
if(cell.theSlider == nil)
{
// Init...
}
Upvotes: 1
Reputation: 4279
You need to store values of slider view and set the values of sliderview in cellForRowAtIndexPath
slider.value = yourvalue;
Upvotes: 2