小编aca*_*era的帖子

IOS:维护uitableviewcell中的按钮状态

我有一个iPhone应用程序问题一直困扰我几天,它似乎不应该是这么困难,所以我敢肯定我错过了一些明显的东西.我已经研究过很多关于"类似"主题的论坛讨论,但实际上并没有解决这个问题.

需要说明的是,如果有一些文档或其他来源我应该研究,请指出正确的方向.

开始...

我有一个项目列表,我在表格中显示给用户(uitableview).每个项目的单元格(uitableviewcell)是自定义的,包含图像和Like按钮(uibutton).正如所料,对于表中的每个项目,用户可以单击"赞"按钮或忽略它.like按钮调用单独的进程来更新服务器.简单吧?

所以,这是问题:

当在特定单元格上单击"赞"按钮时,"选定"状态正常工作,但是当您将单元格滚出视图时,表格中的其他随机单元格将"相似"按钮显示为"已选择",即使它们从未被触摸过.因为细胞被重复使用,出于明显的性能原因,我理解为什么会发生这种情况.我不明白的是为什么我的方法(见下面的代码)不会像我认为的那样覆盖或重置按钮的状态.为简洁起见,我只在此处包含相关代码(希望格式正确):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCustomCell";
    MyCustomViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[MyCustomViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}

    NSString *myRating = [[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"my_rating"];

    // Create the Like button
    UIButton *likeButton = [[UIButton alloc] initWithFrame:CGRectMake(260, 68, 40, 40)];
    [likeButton setImage:[UIImage imageNamed:@"thumbsUp"] forState:UIControlStateNormal];
    [likeButton setImage:[UIImage imageNamed:@"thumbsUpSelected"] forState:UIControlStateSelected];
    if (myRating == @"9") {
        [likeButton setSelected:YES];
    }
    [likeButton setTitle:@"9" forState:UIControlStateNormal];
    [likeButton setTag:indexPath.row];
    [cell.contentView …
Run Code Online (Sandbox Code Playgroud)

uibutton uitableview ios

3
推荐指数
1
解决办法
8099
查看次数

标签 统计

ios ×1

uibutton ×1

uitableview ×1