我使用故事板和自动布局。当我选择first UISwitch并向下滚动时,我看到other UISwitch也打开了,如果我向上滚动,我的第一个UISwitch就会关闭。如何解决这个问题?
我的代码:
- (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];
}
UISwitch* switchView = (UISwitch *)[cell viewWithTag:5];
[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
return cell;
}发布于 2015-08-20 15:06:15
这是因为UITableView重用了UITableViewCell,所以一个单元可以在不同的indexPaths中多次使用,在这种情况下,您有责任维护UITableViewCell subViews的状态。更好的做法是在cellForRowAtIndexPath中返回单元格添加逻辑,以显示/隐藏UISwitch或选择准确的状态,即打开或关闭,您可以将该标志保留在dataSource对象中,然后可以检查该标志,以便为UISwitch设置正确的状态
发布于 2015-08-20 15:15:03
试试这个:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellSetting";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [self.settingsArray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
if ([[self.settingsArray objectAtIndex:indexPath.row] isEqualToString:ROW_PRIVATE_BROWSING])
{
self.privateBrowsingSwitch =[[UISwitch alloc]initWithFrame:CGRectMake(cell.frame.size.width-65, 10, 30, 30)];
if (ApplicationDelegate.privateBrowsing)
{
[self.privateBrowsingSwitch setOn:YES animated:YES];
}
[self.privateBrowsingSwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
[cell addSubview:self.privateBrowsingSwitch];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}发布于 2015-08-20 15:11:25
每次调用cellForRowAtIndexPath时,您都必须替换需要为该位置的单元格显示的特定数据。这包括标签、图片和你的UISwitch。
这是因为UITableViews使用了少量可重用的单元。
在cellForRowAtIndexPath中添加如下内容:
switchView.on = [self isSwitchOnForCellAtIndexPath:indexPath]然后编写确定开关是否应该打开所需的任何逻辑。
https://stackoverflow.com/questions/32111245
复制相似问题