使用标记在tableview中添加自定义按钮

时间:2012-12-23 05:24:47

标签: ios button tags tableview

大家好,           我正在尝试添加带有与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];

}

1 个答案:

答案 0 :(得分:1)

这不能正常工作,因为UITableView 重复使用单元格 当你向下滚动时,第一个单元格不再可见并被重用。

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

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

e.g。

- (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方法中,然后在滚动后也从其他单元格中消失。相同问题:tableview的单元格对象 REUSED 。不要将状态存储在可重用的单元格中!

而是有一个'模型'树或数组来记住状态:text,image,tag,hide:yes / no

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中使用THAT数组并在didSelectEntry中修改它