You are adding a new switch each time the cell is loaded. What you're seeing is many switches stacked on top of each other.
Also, the target action you have set up for your switch won't pass the index path as your selector name is suggesting. I typically use this solution when I don't want to subclass my cells. Getting data from a textfield inside a prototype uicollectionviewcell
Possible solution: Use associated objects to keep track of your switches.
static NSString *kIndexPathKey = @"indexPathKey";
static NSString *kSwitchViewKey = @"switchViewKey";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(10, 5.0, 60.0, 50.0)];
[switchView addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
[self addSwitchView:switchView toCell:cell];
}
UISwitch *switchView = [self switchViewForCell:cell];
[self setIndexPath:indexPath onSwitch:switchView];
switchView.on = [self isIndexPathSelected:indexPath];
return cell;
}
- (void)addSwitchView:(UISwitch *)switchView toCell:(UITableViewCell *)cell {
[cell.contentView addSubview:switchView];
[cell setAssociatedObject:switchView forKey:kSwitchViewKey];
}
- (UISwitch *)switchViewForCell:(UITableViewCell *)cell {
return [cell associatedObjectForKey:kSwitchViewKey];
}
- (void)switchValueChanged:(UISwitch *)sender {
NSIndexPath *indexPath = [self indexPathOfSwitch:sender];
[self setRowSelected:sender.isOn atIndexPath:indexPath];
[self.delegate didSelectItem:[self itemAtIndexPath:indexPath] atIndexPath:indexPath selected:sender.isOn sender:self];
}
- (void)setIndexPath:(NSIndexPath *)indexPath onSwitch:(UISwitch *)switchView {
[switchView setAssociatedObject:indexPath forKey:kIndexPathKey];
}
- (NSIndexPath *)indexPathOfSwitch:(UISwitch *)switchView {
return [switchView associatedObjectForKey:kIndexPathKey];
}
@implementation NSObject (AssociatedObjects)
- (void)setAssociatedObject:(id)object forKey:(NSString *const)key {
objc_setAssociatedObject(self, (__bridge const void *)(key), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id)associatedObjectForKey:(NSString *const)key {
return objc_getAssociatedObject(self, (__bridge const void *)(key));
}
@end
Note that everything above that is using associated objects could be done by using a custom subclass of UITableViewCell
. However, there are many advantages to not subclassing.
Composition > Inheritance.