主要是通过cell.accessoryView来添加switch控件
- (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] autorelease];
//add a switch
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
[switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchview;
[switchview release];
}
cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
return cell;
}
.h文件中添加:
- (IBAction) updateSwitchAtIndexPath:(id) sender;
获取switch数据:
- (IBAction)updateSwitchAtIndexPath:(id)sender {
UISwitch *switchView = (UISwitch *)sender;
if ([switchView isOn])
{
//do something..
}
else
{
//do something
}
}