0

在我的应用程序中,我在表格视图中添加了一个滑块,即每一行都包含一个滑块,它也可以正常工作。

但是当我滚动表格视图时,滑块会重新加载,即每个都显示我的起始位置而不是滑块值。

//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;
}

我该如何解决这个问题?

4

4 回答 4

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;

这样,只有当单元格为 nil 时才会创建滑块,即创建单元格。并使用tableView:willDisplayCell:forRowAtIndexPath:方法设置滑块值,如 slider.value = yourvalue;

于 2013-02-21T11:25:44.387 回答
2

您需要存储滑块视图的值并将滑块视图的值设置为cellForRowAtIndexPath slider.value = yourvalue;

于 2013-02-21T11:20:17.520 回答
1

问题是,cellForRowAtIndexPath它不仅被调用一次,而且每次 tableView 需要渲染该单元格时......所以你必须确保只theSlider调用第一次初始化......

最好的方法是定义一个自定义UITableViewCell并放置一个可以存储的属性theSlider,然后在cellForRowAtIndexPath调用时检查它是否已经初始化,请参阅:

// If the slider is not yet initialized, then do it
if(cell.theSlider == nil)
{
    // Init...
}
于 2013-02-21T11:22:54.100 回答
1

这真是从“ cellForRowAtIndexPath”法。每次滚动时,每个单元格都会获取nil并重新初始化它。更好的是,您可以尝试创建自定义单元格类(通过创建 的子类UITableViewCell)以及条件“if (cell == nil)”中的定义滑块。

于 2013-02-21T11:29:51.313 回答