SOF
SOF

Reputation: 457

How to add switch in tableview cells

My application navigation based and view is UITableviewController. I need to add switch control for ON and OFF for particular UIViewtable cell. How to add.

Upvotes: 1

Views: 9631

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

You can add a switch in the -tableView:cellForRowAtIndexPath: method found in the UITableViewDataSource Protocol

- (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];
    }

    // Configure the cell...
    UISwitch *aSwitch = [[[UISwitch alloc] init] autorelease];
    [aSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    [cell.contentView addSubview:aSwitch];
    return cell;
}

Upvotes: 3

DarkDust
DarkDust

Reputation: 92335

Also a classic, this question has been asked a lot here already. For example, see this question. Search for UITableView and UISwitch to get way more results.

Upvotes: 3

Related Questions