我坚持这个。我将用我的代码解释
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSNumber *cellno=[NSNumber numberWithUnsignedInteger:indexPath.row];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 13, 15,18)];
imgView.image=[UIImage imageNamed:@"lock.png"];
tickView = [[UIImageView alloc] initWithFrame:CGRectMake(200, 13, 15,18)];
tickView.image=[UIImage imageNamed:@"tick.png"];
switch (indexPath.row) {
case 0:
cell.textLabel.text=@"apples";
if ([appDelegate.connected containsObject:cellno]) { //condition
[cell.contentView addSubview:tickView];
}else{
[cell.contentView addSubview:imgView];
}
break;
}
cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
在第一次加载tableview时,'imgView'子视图被添加到单元格内容视图中,并且在一些操作之后满足'if'条件并添加'tickView'。
问题是,旧视图未被隐藏或删除,因此两个图像都会出现。
非常感谢帮助
答案 0 :(得分:0)
不是在cellForRowAtIndexPath
方法中创建imgView和tickView视图,而是在创建单元格时创建它们并将其重用于单元格。然后你可以这样做:
...
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 13, 15,18)];
imgView.image=[UIImage imageNamed:@"lock.png"];
tickView = [[UIImageView alloc] initWithFrame:CGRectMake(200, 13, 15,18)];
tickView.image=[UIImage imageNamed:@"tick.png"];
}
...
if ([appDelegate.connected containsObject:cellno]) { //condition
[imgView removeFromSuperview];
[cell.contentView addSubview:tickView];
}else{
[tickView removeFromSuperview];
[cell.contentView addSubview:imgView];
}