滚动时UITableviewCell问题

时间:2013-08-27 11:18:37

标签: iphone ios uitableview

我动态创建了表格视图,在cellForRowAtIndexPath中,我在单元格上添加了一个自定义按钮作为子视图

if ([deviceNameArray count]!=0)
{
    pairButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pairButton.frame = CGRectMake(230.0f, 10.0f, 70.0f, 25.0f);
    [pairButton setTitle:@"Connect" forState:UIControlStateNormal];
    pairButton.titleLabel.textColor = [UIColor lightGrayColor];
    pairButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    pairButton.titleLabel.font = [UIFont fontWithName:@"arial" size:10];

    pairButton.tag = indexPath.row;

    [pairButton addTarget:self action:@selector(connectToDevice:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:pairButton];
    isPairButtonAdded = YES;

}

我用另一台设备成功后,我已将设备的按钮标题更改为断开连接。现在问题是每当我滚动我的表断开连接但我不想发生这样的事情,我知道它由于细胞娱乐如何停止重建细胞。

3 个答案:

答案 0 :(得分:2)

您必须在阵列中存储已连接和已断开连接的设备的记录,然后您可以像这样管理您的单元

if ([deviceNameArray count]!=0)
{
    pairButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pairButton.frame = CGRectMake(230.0f, 10.0f, 70.0f, 25.0f);

    if([device isConnected]) // Get object from array and check is it coonected or disconnected
    {
       [pairButton setTitle:@"Connect" forState:UIControlStateNormal];
    }
    else
    {
        [pairButton setTitle:@"Disconnected" forState:UIControlStateNormal];
    }
pairButton.titleLabel.textColor = [UIColor lightGrayColor];
pairButton.titleLabel.textAlignment = NSTextAlignmentCenter;
pairButton.titleLabel.font = [UIFont fontWithName:@"arial" size:10];

pairButton.tag = indexPath.row;

[pairButton addTarget:self action:@selector(connectToDevice:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:pairButton];
isPairButtonAdded = YES;

}

答案 1 :(得分:0)

您无法在cellForRowAtIndexPath:中执行此操作:

// dequeue cell
if (!cell) {
    // create cell
}
// create button

相反,您必须在单元格创建块内创建按钮。否则,每次单元格出现在屏幕上时,将再次创建一个新按钮。

答案 2 :(得分:0)

我解决了这个问题,在我正在检查

的条件下装箱我的按钮
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    if ([deviceNameArray count]!=0)
    {
        pairButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        pairButton.frame = CGRectMake(230.0f, 10.0f, 70.0f, 25.0f);
        [pairButton setTitle:@"Connect" forState:UIControlStateNormal];
        pairButton.titleLabel.textColor = [UIColor lightGrayColor];
        pairButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        pairButton.titleLabel.font = [UIFont fontWithName:@"arial" size:10];

        pairButton.tag = indexPath.row;

        [pairButton addTarget:self action:@selector(connectToDevice:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:pairButton];
        isPairButtonAdded = YES;

    }

现在已经解决了