2010-09-22 34 views
72

如何在UITableView单元上嵌入UISwitch?示例可以在设置菜单中看到。UITableView单元中的UISwitch

我目前的解决方案:

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

你目前的做法有什么问题吗? – MobileMon 2013-08-26 15:14:05

回答

183

将其设置为accessoryView通常是要走的路。您可以在tableView:cellForRowAtIndexPath:中进行设置您可能希望在切换开关时使用目标/操作来执行某些操作。像这样:

- (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"); 
} 
+1

而不是MY_SWITCH_CELL应该是我认为对应的单元格编号。很好的解决方案! – testing 2010-09-23 09:10:40

+2

aCell.accessoryView = switchView; – konradowy 2011-07-23 08:56:51

+0

你如何用括号表示法编写'aCell.accessoryView = switchView;'? – Jesse 2012-06-19 16:03:58

10

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

2

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

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

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

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

+0

我更喜欢编程解决方案(尽管它是设置页面),但我也对前两个选项的工作方式感兴趣。也许你可以更详细地解释一下它们。 – testing 2010-09-22 17:11:34

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

为什么使用'initWithFrame'?你为什么使用'addSubview'? 'switch'不能用作变量名称。 – testing 2010-09-22 17:06:31

+0

对不起,交换机名称。我有一些代码..我只是改变它的变量名称。 – kthorat 2010-09-23 15:09:41

+0

它为我工作。有效的解决方案,代码少。 – 2014-07-24 11:23:19