Один простой подход может быть таким:
Вы хотите, чтобы пользователь мог включать только одну строку за раз.Для этого вам нужно будет отслеживать две вещи: сначала переключатели (мы можем получить к ним доступ через вспомогательное представление ячейки), а затем - включенный переключатель (для этого предположим, что мы используем свойство тега).
So we will need:
>One variable to keep track of which row's switch is on.
>Array which will hold the of the switches.
Я создал пример приложения со следующим кодом: (Я принимаю число строк в качестве константы до 10)
Код
SwitchTableController.h
#import <UIKit/UIKit.h>
#define NUMBER_OF_ROWS 10
@interface SwitchTableController : UITableViewController {
int selectedSwitchRow;
NSMutableArray *switchArray;
}
@end
Код SwitchTableController.m
#import "SwitchTableController.h"
@implementation SwitchTableController
#pragma mark -
#pragma mark View lifecycle
- (void)dealloc {
[switchArray release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
selectedSwitchRow = -1;
if (switchArray == nil)
{
switchArray = [[NSMutableArray alloc] initWithCapacity:10];
}
for (int i=0; i<NUMBER_OF_ROWS; i++)
{
UISwitch *switchController = [[UISwitch alloc] initWithFrame:CGRectZero];
[switchController setOn:NO animated:YES];
switchController.tag = i;
[switchController addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchArray addObject:switchController];
[switchController release];
}
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return NUMBER_OF_ROWS;
}
- (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];
}
cell.accessoryView = [switchArray objectAtIndex:indexPath.row];
return cell;
}
-(void) switchChanged:(UISwitch *)sender
{
if (selectedSwitchRow >= 0 && selectedSwitchRow<[switchArray count] && selectedSwitchRow != sender.tag)
{
UISwitch *tempSwitch = [switchArray objectAtIndex:selectedSwitchRow];
[tempSwitch setOn:NO animated:YES];
[self.tableView reloadData];
}
selectedSwitchRow = sender.tag;
}