ios - UIButton 图像在多个 UITableViewCells 中更改

标签 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];
}

谢谢!

最佳答案

您需要有一个在触摸按钮时设置的属性,您在 cellForRowAtIndexPath 中 checkin 。因此,在按钮的方法中,有一个属性,比如 lastTouched(@property (strong,nonatomic) NSIndexPath *lastTouched,或者 NSInteger,如果你没有部分),你设置为的 indexPath(或 indexPath.row)触摸按钮所在的单元格(从您通过搜索按钮的 super View 直到找到单元格,或者通过在按钮上使用等于 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 图像。

关于ios - UIButton 图像在多个 UITableViewCells 中更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038987/

相关文章:

ios - 使用 OAuth 1 的 Swift (Xcode) REST API 连接

iphone - 核心数据 SQLite 约束失败

ios - 如何本地化静态 UIApplicationShortcutItems?

IOS/objective-C :Animation of Multiple CGAffineTransformations

ios - 设置Dynamic Cell的Table View Content height为table view height constraints ios

cocoa-touch - NSFetchedResultsController 委托(delegate)异常

ios - iOS 中的 UIWebView 本地视频/音频播放无法使用 Meteor (PhoneGap)

iphone - 创建动态填充 NSMutableArrays 的 NSMutableDictionary

iphone - 如何在 swift ios 中将图像宽度与屏幕尺寸相匹配

iphone - TableViewCells 和字典数组