2010-09-22 37 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