在UITableView单元格中的UISwitch

我如何在UITableView单元上embeddedUISwitch ? 示例可以在设置菜单中看到。

我目前的解决scheme

 UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease]; cell.accessoryView = mySwitch; 

将其设置为accessoryView通常是要走的路。 你可以在tableView:cellForRowAtIndexPath:设置它tableView:cellForRowAtIndexPath:当开关被翻转时,你可能希望使用target / action来做某些事情。 像这样:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { switch( [indexPath row] ) { case MY_SWITCH_CELL: { UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"]; if( aCell == nil ) { aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease]; aCell.textLabel.text = @"I Have A Switch"; aCell.selectionStyle = UITableViewCellSelectionStyleNone; UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero]; aCell.accessoryView = switchView; [switchView setOn:NO animated:NO]; [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; [switchView release]; } return aCell; } break; } return nil; } - (void)switchChanged:(id)sender { UISwitch *switchControl = sender; NSLog( @"The switch is %@", switchControl.on ? @"ON" : @"OFF" ); } 

您可以添加一个UISwitch或任何其他控件到单元的accessoryView 。 这样它会出现在单元格的右侧,这可能是你想要的。

 if (indexPath.row == 0) {//If you want UISwitch on particular row UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; [cell addSubview:theSwitch]; cell.accessoryView = theSwitch; } 

您可以在Interfacebuilder中准备单元,将其链接到您的Viewcontroller的IBOutlet,并在tableview要求正确的行时将其返回。

相反,您可以为单元格创build一个单独的xib(再次使用IB),并在创build单元格时使用UINib加载它。

最后,您可以编程创build开关,并将其添加到您的单元格contentview或accessoryview。

哪一个最适合你,主要取决于你喜欢做什么。 如果你的桌面内容是固定的(对于设置页面等),前两个可能工作得很好,如果内容是dynamic的,我宁愿编程解决scheme。 请更具体地说,你想做什么,这将使回答你的问题更容易。