【发布时间】:2012-02-23 23:31:41
【问题描述】:
我有一个 iPhone 应用程序问题困扰了我好几天,而且看起来真的不应该这么难,所以我确定我遗漏了一些明显的东西。我研究了很多关于“类似”主题的论坛讨论,但没有任何具体解决这个问题。
为了清楚起见,如果我应该研究一些文档或其他来源,请指出正确的方向。
来了……
我有一个在表格 (uitableview) 中显示给用户的项目列表。每个项目的单元格 (uitableviewcell) 是自定义的,包含一个图像和一个赞按钮 (uibutton)。正如预期的那样,对于表中的每个项目,用户都可以单击 Like 按钮或忽略它。点赞按钮调用一个单独的进程来更新服务器。很简单吧?
那么,问题来了:
当在特定单元格上单击 Like 按钮时,Selected 状态工作正常,但当您将单元格滚动到视图之外时,表格中的其他随机单元格将 Like 按钮显示为 Selected,即使它们从未被触摸过。由于单元被重复使用,出于明显的性能原因,我理解为什么会发生这种情况。我不明白为什么我的方法(见下面的代码)不会像我认为的那样覆盖或重置按钮的状态。为简洁起见,我只在此处包含相关代码(希望格式正确):
- (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 addSubview:likeButton];
[likeButton addTarget:self action:@selector(likeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (void)likeButtonPressed:(UIButton *)sender {
// Changed the Selected state on the button
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
// Create a new object with the user's rating and then replace it in the dataArray
NSString *ratingText = sender.titleLabel.text;
NSMutableArray *myMutableArray = [[self.dataArray objectAtIndex:row] mutableCopy];
[myMutableArray setValue:ratingText forKey:@"my_rating"];
[self.dataArray replaceObjectAtIndex:row withObject:myMutableArray];
}
所以,我已经经历了很多次迭代,但我似乎无法获得按钮的状态来显示那些被喜欢的项目的选定图像并为那些没有被喜欢的项目保留正常图像喜欢。
任何帮助或建议将不胜感激。
【问题讨论】:
-
我也有同样的问题。我在 tableView 的 HeaderSection 中有一个单选按钮。当我在 headerSection 中选择一个按钮时,会在 tableView 中选择随机单选按钮。你解决了你的问题。你能帮我么。?我必须在 tableView 中选择单个 radioButton。
标签: ios uitableview uibutton