我的第一个单元格中没有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;
}
答案 0 :(得分:2)
如果切换器是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;
}
问题发生的原因是重用单元格,当您不需要时,必须清除单元格(删除开关)。 它应该工作。
答案 1 :(得分:1)
您需要使用prepareForReuse
方法重置单元格。当您从tableview中取出单元格时,单元格不会重置,旧值仍在单元格上!