我需要实现这个功能。请帮帮我。在"unblockbtnClick"之后,点击改变图像,没问题,但是当滚动tableview时,选中的图像都变成了之前的图像。
这是我的代码。
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"BlockedCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
NSArray *nib;
nib = [[NSBundle mainBundle] loadNibNamed:@"BlockedCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
[btn_tblvcAddbtn addTarget:self action:@selector(unblockbtnClick:) forControlEvents:UIControlEventTouchUpInside];
[btn_tblvcAddbtn setTag:indexPath.row];
return cell;
}
-(IBAction)unblockbtnClick:(UIButton *)sender{
NSLog(@"Value of selected button = %ld",(long)[sender tag]);
[sender setBackgroundImage:[UIImage imageNamed:@"remove.png"] forState:UIControlStateNormal];
}
您需要在if
条件之外分配nib文件
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
// initialize cell here
}
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BlockedCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
-(IBAction)unblockbtnClick:(id)sender
{
UIButton *btn=(UIButton *)sender;
UITableViewCell *cellll;
if([[[UIDevice currentDevice] systemVersion] intValue]<6)
cellll=(UITableViewCell *)[btn superview];
else
cellll=(UITableViewCell *)[[btn superview]superview];
NSIndexPath *aaa=[tblOption indexPathForCell:cellll];
if([ArrSelectedData containsObject:[TblDataArrr objectAtIndex:aaa.row]])
{
//tblDataArr is table dataArray && ArrSelectedData is a array which contain selected itme of table
[ArrSelectedData removeObject:[TblDataArrr objectAtIndex:aaa.row]];
[btn setBackgroundImage:[UIImage imageNamed:@"blank_checkbox.png"] forState:UIControlStateNormal];
}
else
{
[ArrSelectedData addObject:[TblDataArrr objectAtIndex:aaa.row]];
[btn setBackgroundImage:[UIImage imageNamed:@"tick_checkbox.png"] forState:UIControlStateNormal];
}
}
和cellForRowAtIndexPath
{
if([ArrSelectedData containsObject:[TblDataArrr objectAtIndex:indexPath.row]])
[tempBtn setBackgroundImage:[UIImage imageNamed:@"tick_checkbox.png"] forState:UIControlStateNormal];
else
[tempBtn setBackgroundImage:[UIImage imageNamed:@"blank_checkbox.png"] forState:UIControlStateNormal];
}
当你滚动一个单元格出屏幕,然后返回- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
方法被调用。你没有设置背景,这就是它被重置的原因。
要修复,您需要存储有关选定单元格的信息,并在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
中检查它,并相应地应用适当的背景