在我的应用程序中,我在表格视图中添加一个滑块,即每行包含一个滑块&它也可以正常工作。
但是当我滚动表格视图时,滑块会重新加载,即每个都显示我的起始位置而不是滑块值。
//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;
}
我该如何解决?
答案 0 :(得分:3)
- (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;
这样,只有当cell为nil时才会创建滑块,即创建单元格。并使用tableView:willDisplayCell:forRowAtIndexPath:方法设置滑块值,如slider.value = yourvalue;
答案 1 :(得分:2)
您需要存储滑块视图的值,并在cellForRowAtIndexPath
slider.value = yourvalue;
答案 2 :(得分:1)
问题是cellForRowAtIndexPath
不仅被调用一次,而且每次tableView需要渲染该单元格时......所以你必须确保只在第一次初始化theSlider
时称为...
最好的方法是定义自定义UITableViewCell
并放置一个存储theSlider
的属性,然后,当调用cellForRowAtIndexPath
时,检查它是否已经初始化,见:
// If the slider is not yet initialized, then do it
if(cell.theSlider == nil)
{
// Init...
}
答案 3 :(得分:1)
这实际上来自“cellForRowAtIndexPath
”方法。每当您滚动每个单元格时,都会获得nil
并重新初始化它。您可以尝试创建自定义单元格类(BY创建UITableViewCell
的子类)以及条件“if (cell == nil)
”中的定义滑块。