2

大家好,我正在尝试添加带有与 indexPath.row 相关的标签的自定义按钮。如果我不将新行插入到 tableview 中,我可以正确查看标签值。但是,当我插入新行时,如果插入的行不在 0 到 9 之间(iphone 5 可以显示),我的新行标签值不正确。在 iphone 上,我需要向下滚动才能看到。


但是,使用相同的代码,我可以在 ipad 上正确获取我的标签值。我不需要向下滚动 ipad 上的表格视图来查看我的所有行。我想知道它为什么会发生以及如何解决。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"dialoguesTableCell";
    dialoguesCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[dialoguesCell alloc] initWithStyle:UITableViewCellStyleDefault 
            reuseIdentifier:CellIdentifier];

    }

    UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [yourButton setImage:[UIImage imageNamed:@"1StarBlank.png"]     forState:UIControlStateNormal];
    [yourButton setTitle:@"Button" forState:UIControlStateNormal];
    [yourButton addTarget:self action:@selector(buttonSelected:)   forControlEvents:UIControlEventTouchUpInside];
    yourButton.tag=indexPath.row;
    yourButton.frame = CGRectMake(5, 10, 40, 25);
    [cell addSubview:yourButton];
    return cell;


}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath    *)indexPath
{
   NSIndexPath *indexPathstoinsert = [NSIndexPath indexPathForRow:indexPath.row+1     inSection:section];
   NSArray *indexPathsToInsertArray = [NSArray arrayWithObject:indexPathstoinsert];
   [[self mainTableView] insertRowsAtIndexPaths:indexPathsToInsertArray withRowAnimation:UITableViewRowAnimationRight];

}
4

1 回答 1

1

这无法正常工作,因为 UITableView在您向下滚动时重用单元格
,第一个单元格不再可见并被重用。

如果表格是..“小”,您可以通过不重复使用单元格来解决它
但是如果表格不仅仅是几个条目而是大量数据,您真的想改变自己的方式

为按钮分配标签:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

例如

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    UIButton *b = nil;
    for(UIView *v in cell.subviews) {
        if([v isKindOfClass:[UIButton class]]) {
            b = (UIButton*)v;
            break;
        }
    }

    b.tag = indePath.row;
}

在评论中您提到了另一个问题:按钮隐藏在您的didSelectRow方法中,然后在滚动后也从其他单元格中消失。同样的问题:单元格对象被表格视图重用。不要将状态存储在可重复使用的单元格中!

而是有一个“模型”树或数组来记住状态:文本、图像、标签、隐藏:是/否

NSArray *myTableContents

 NSMutableDictionary *d1 = [@{@"text:@"bla", @"hidden":@NO} mutableCopy];
 NSMutableDictionary *d2 = [@{@"text:@"bloo", @"hidden":@NO} mutableCopy];
 NSMutableDictionary *d3 = [@{@"text:@"foo", @"hidden":@NO} mutableCopy];
 myTableContents = @[d1,d2,d3];

然后总是在 numberOfRows 和 viewForRow 中使用那个数组并在 didSelectEntry 中修改它

于 2012-12-23T09:04:38.567 回答