I am creating a function for this case, and its work is good for me .. try it, first in creating the cell you can check the line where you want to add UISwitch
, for example,
if(indexPath.row == 0) [self createOnOffView:cell withTitle:@"Somthing" withTag:1001 defaultVal:YES];
And function:
- (void) createOnOffView:(UITableViewCell*) cell withTitle:(NSString*) title withTag:(int)tag defaultVal:(BOOL) defaultVal { CGRect rect; cell.textLabel.text = title; cell.selectionStyle = UITableViewCellSelectionStyleNone; rect = cell.contentView.frame; if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) rect.origin.x = cell.frame.size.width - 20; else rect.origin.x = rect.size.width/2 +35; rect.origin.y = rect.size.height/2 - 15; rect.size.width = 60; UISwitch *switchView = [[UISwitch alloc] initWithFrame:rect]; [cell.contentView addSubview:switchView]; [switchView addTarget:self action:@selector(didChangeSwitch:) forControlEvents:UIControlEventValueChanged]; switchView.tag = tag; [switchView setOn:defaultVal]; [switchView release]; }
And when the value is a change, this method will be launched. So you can find out which switch is tag based
- (void) didChangeSwitch:(UISwitch*)switchView { if(switchView.tag == 1001) {
Hope this will be helpful :)
source share