0

我已经动态创建了表格视图,在 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;

}

与我的另一台设备成功后,我已将设备的按钮标题更改为断开连接。现在的问题是每当我滚动我的表格断开连接变成连接但我不希望那样发生,我知道它是由于单元格娱乐如何停止重新创建单元格。

4

3 回答 3

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;

}

于 2013-08-27T11:33:08.257 回答
0

你不能这样做cellForRowAtIndexPath:

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

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

于 2013-08-27T11:31:50.117 回答
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;

    }

现在它解决了

于 2013-08-27T11:37:31.790 回答