【发布时间】:2017-10-09 08:50:05
【问题描述】:
我在 tableview 数据源函数之一中以编程方式创建 UISwitch(索引处的行单元格)。当我滚动表格视图时,关闭状态开关出现故障(UI)出现了两轮。附上开关截图。
感谢您的帮助!
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *title = (UILabel*)[cell viewWithTag:80];
UILabel *description = (UILabel*)[cell viewWithTag:81];
UIView *innerView = (UIView *)[cell viewWithTag:82];
innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0] CGColor];
innerView.layer.borderWidth = 2.0f;
NSDictionary *displayDict = scenarioListsArray[indexPath.row];
title.text =[displayDict objectForKey:@"name"];
description.text = [displayDict objectForKey:@"description"];
UISwitch *myswitch = [[UISwitch alloc]initWithFrame:CGRectMake(cell.contentView.frame.size.width-60, (cell.contentView.frame.size.height/2)-20 , 100, 100)];
myswitch.onTintColor = [UIColor colorWithRed:25/255.0f green:122/255.0f blue:66/255.0f alpha:1];
[cell.contentView addSubview:myswitch];
myswitch.tag = indexPath.row;
[myswitch addTarget:self action:@selector(cellButtonClickAction:) forControlEvents:UIControlEventValueChanged];
if ([[displayDict objectForKey:@"status"] isEqualToString:@"ACTIVE"]) {
[myswitch setOn:YES animated:YES];
}
else
{
[myswitch setOn:NO animated:YES];
}
return cell;
}
【问题讨论】:
-
按数组管理单元格的可重用性,您的问题将得到解决
-
@Vinod Radhakrishnan 您也可以在表格单元格类的 prepareForReuse 方法中设置开关的默认值。
-
我已经更新了我的代码。你能解释一下吗? @iPatel
-
"if ([[displayDict objectForKey:@"status"] isEqualToString:@"ACTIVE"])": 如果开关状态,改变,我清楚地跳你更新
displayDict。还有[cell.contentView addSubview:myswitch];NO。避免这种情况,细胞被重复使用(也被称为两次)。为什么不将其添加到自定义单元格中,并在不需要时将其隐藏? -
@Larme 这是我的错误,它实际上是注释代码。我也会在这里更正它。
标签: ios objective-c uitableview uiswitch