单击特定tableview单元格上的按钮后,按钮会单击并更改为复选标记。但是,其他单元格也会变为复选标记。并重新加载tableview不会使复选标记消失。我知道这与可重复使用的细胞有关。但是如何从单击单元格按钮时调用的方法更新cellForRowAtIndex?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Configure the cell...
static NSString *ReusableIdentifier = @"Cell";
SetListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableIdentifier forIndexPath:indexPath];
cell.delegate = self;
if ([self.selectedRows containsIndex:indexPath.row]) {
[cell.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];
}
else {
[cell.plusButton setBackgroundImage:plusImage forState:UIControlStateNormal];
}
return cell;
}
自定义单元格类中的方法。
- (IBAction)addSongButtonPressed:(UIButton *)sender
{
[self.delegate addSongButtonPressedOnCell:self];
UIImage *checkImage = [UIImage imageNamed:@"check.png"];
[self.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];
}
来自小组代表的方法。
-(void)addSongButtonPressedOnCell:(id)sender
{
NSIndexPath *indexPath = [self.searchTableView indexPathForCell:sender];
NSMutableDictionary *track = [self.searchTracks objectAtIndex:indexPath.row];
[self.selectedRows addIndex:indexPath.row];
}
答案 0 :(得分:1)
您需要跟踪单元格外部的选择状态 - 单元格是一个瞬态对象,它显示数据模型中的信息,您无法使用它来存储状态。
由于您的跟踪数据有不可变的词典,因此您需要添加其他数据结构来存储您的选择状态。我会使用NSMutableSet
。
向视图控制器添加属性
@property (strong,nonatomic) NSMutableSet *selectedRows;
并在viewDidLoad
self.selectedRows=[NSMutableSet new];
然后您可以用来跟踪/检查选择状态 -
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Configure the cell...
static NSString *ReusableIdentifier = @"Cell";
SetListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReusableIdentifier forIndexPath:indexPath];
NSDictionary *track = [self.searchTracks objectAtIndex:indexPath.row];
cell.searchSongTitle.text = [track objectForKey:@"title"];
cell.searchArtist.text = [[track objectForKey:@"user"]objectForKey:@"username"];
cell.plusButton.tag=indexPath.row;
if ([self.selectedRows containsIndex:indexPath.row]) {
[cell.plusButton setBackgroundImage:checkImage forState:UIControlStateNormal];
}
else {
[cell.plusButton setBackgroundImage:nil forState:UIControlStateNormal];
}
//If there is no picture available. Adds a Custom picture.
if ([[track objectForKey:@"artwork_url"] isEqual:[NSNull null]]){
cell.searchAlbumArtImage.image = [UIImage imageNamed:@"SoundCloudLogo"];
}
else{
//Init the cell image with the track's artwork.
UIImage *cellImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[track objectForKey:@"artwork_url"]]]];
cell.searchAlbumArtImage.image = cellImage;
}
return cell;
}
然后按下按钮处理程序变为 -
- (IBAction)cellAddSongButtonPressed:(UIButton *)sender {
NSInteger index = sender.tag;
[self.selectedRows addIndex:index];
[sender setBackgroundImage:checkImage forState:UIControlStateNormal];
}
创建Track
课程而不是使用NSDictionary