如何在UITableViewCell中访问UIButton或UILabel



我有一个 20 行的UITableView。在每一行中,添加了两个UIButton,所以我总共有 40 个按钮。如何访问每个单元格中的每个按钮?所有这些UIButton都有两个tag s 1 和 2。

例如:我想编写一个方法来更改特定行中 2 个按钮的背景颜色:

-(void)changeColor:(int)row{
     //code here
}

你有什么建议吗?

-(UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil){
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:@"Cell"] autorelease];
        UIButton *button1=[[UIButton alloc] initWithFrame:CGRectMake(x1,y1,w1,h1)];
        UIButton *button2=[[UIButton alloc] initWithFrame:CGRectMake(x2,y2,w2,h2)];       
        [button1 setTag:1];
        [button2 setTag:2];
        [[cell contentView] addSubview:button0 ];
        [[cell contentView] addSubview:button1 ];
        [button0  release];
        [button1  release];        
    }
    UIButton *button1  = (UIButton *)[cell viewWithTag:1];
    UIButton *button2  = (UIButton *)[cell viewWithTag:2];
    return cell;
}

你应该能够做到这一点:

-changeColor:(int)row
{
    NSIndexPath indexPath = [NSIndexPath indexPathForRow:row inSection:0]; // Assuming one section
    UITableViewCell *cell = [myTableView cellForRowAtIndexPath:indexPath];
    UIButton *button1 = (UIButton *)[[cell contentView] viewWithTag:1];
    UIButton *button2 = (UIButton *)[[cell contentView] viewWithTag:2];
}

*某些语法可能是错误的。我手边没有 Xcode

如果您想更改按钮颜色以突出显示/向下状态,我建议使用以下:

[yourButton addTarget:self action:@selector(goToView:) forControlEvents:UIControlEventTouchUpInside];
[yourButton addTarget:self action:@selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self action:@selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];
-(void)buttonAction:(UIButton*)sender
{
    [self touchCancel:sender];
    /* DO SOME MORE ACTIONS */
}
-(void)changeColor:(UIButton*)sender
{
    sender.backgroundColor = [UIColor redColor];
}
-(void)touchCancel:(UIButton*)sender
{
    sender.backgroundColor = [UIColor clearColor];
}

如果要使按钮具有不同的选定颜色,请创建一个包含所有选定状态的数组。然后使用该数组检查按钮颜色是否需要在cellForRowAtIndexPath中使用不同的颜色。

当您想更改按钮颜色时,只需更改数组中的值并调用

[self.tableView reloadData];

请务必在 if(单元格 == nil)方法之外执行此操作,以便在重用单元格时也会调用它。

最新更新