UIButton图像在多个UITableViewCells中更改

时间:2013-11-18 02:17:52

标签: ios objective-c uitableview uibutton

我目前正在构建一个iOS应用程序,它使用UITableView和包含按钮的自定义UITableViewCells。我想要实现的是让UIButton的图像在内部触摸时发生变化。那部分工作正常,问题是当你滚动时,UITableViewCell中的每几个按钮突然都有这个新图像。下面是我的一些代码。任何帮助将不胜感激。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID = @"CellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];

        //YEP BUT
        yepBut = [[UIButton alloc] initWithFrame:CGRectMake(23, 16, 64, 32.5)];

        [yepBut addTarget:self action:@selector(yepPost:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:yepBut];
    }
    [yepBut setImage:[UIImage imageNamed:@"yepBtn"] forState:UIControlStateNormal];
    return cell;
}

-(void) yepPost:(id) sender{
    //UIButton *clicked = (UIButton *) sender;
    [sender setImage:[UIImage imageNamed:@"yepBtnACT"] forState:UIControlStateNormal];
}

谢谢!

2 个答案:

答案 0 :(得分:2)

您需要拥有一个属性,当您触摸按钮时设置属性,并检查cellForRowAtIndexPath。所以,在按钮的方法中,有一个属性,比如lastTouched(@property(强,非原子)NSIndexPath * lastTouched,或NSInteger,如果你没有部分),你设置为indexPath(或indexPath.row)触摸按钮所在的单元格(通过搜索按钮的超级按钮直到找到单元格,或通过使用等于indexPath.row的按钮上的标记从单元格获取)。之后,您必须reloadData或reloadRowsAtIndexPaths才能进行更改。在cellForRowAtIndexPath中,您可以像这样设置图像:

if ([self.lastTouched isEqual:indexPath]) {
    [yepBut setImage:[UIImage imageNamed:@"yepBtnACT"] forState:UIControlStateNormal];
else{
    [yepBut setImage:[UIImage imageNamed:@"yepBtn"] forState:UIControlStateNormal];
}

当你第一次初始化lastTouched时,你想把它设置为你的表中没有出现的indexPath,所以在你触摸之前没有任何东西会有yepButAct图像。

答案 1 :(得分:0)

对UITableViewCell进行子类化修复了我的问题。

相关问题