[英]Appearing UISwitch in wrong cell of UITableView
我的第一个单元格中没有UISwitch,但滚动后突然出现,我不明白为什么?!
我将不胜感激一些建议甚至更好的一些编码思想!
谢谢!
截图 https://www.dropbox.com/sh/qxoc0yidpzxkfgv/gLra_Ilsuv
-
我的密码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SettingObject *settingObjectCell = [[[settingsItems objectAtIndex:indexPath.section] valueForKey:@"SectionItems"]objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"SettingsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Selected row - custiomize
UIView *customColorView = [[UIView alloc] init];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// add UISwitcher
if ([settingObjectCell.switcher isEqualToString:@"YES"] || [settingObjectCell.switcher isEqualToString:@"NO"])
{
UISwitch *switcher = [[UISwitch alloc] initWithFrame:CGRectZero];
//place for switcher
cell.accessoryView = switcher;
// load settings or get default
NSString *switchYesNo = [settingsLoadedUserDefault objectForKey:[settingObjectCell title]] ? [settingsLoadedUserDefault objectForKey:[settingObjectCell title]] : settingObjectCell.switcher ;
// add value to switcher
[switcher setOn:[switchYesNo boolValue]];
// action for switcher
[switcher addTarget:self action:@selector(updateSwitch:) forControlEvents:UIControlEventValueChanged];
// selection Turn OFF
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text = [settingObjectCell title];
cell.detailTextLabel.text = [settingObjectCell subtitle];
return cell;
}
如果切换器是NSString类型,则应使用isEqualToString:而不是isEqual:。 将您的if语句更改为:
if ([settingObjectCell.switcher isEqualToString:@"YES"] || [settingObjectCell.switcher isEqualToString:@"NO"])
{
// Your existing code
}
else
{
//Move this line here
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// remove switch
cell.accessoryView = nil;
}
发生此问题是由于重复使用单元格,您在不需要时必须清除该单元格(删除开关)。 它应该工作。
您需要在prepareForReuse
方法上重置单元格。 当您从表格视图中退出单元格时,该单元格不会重置并且旧值仍在该单元格上!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.