2011-03-17 75 views
0

我是IOS編程的新手,我遇到問題。我已經得到了我以動態方式UISwitch在每個單元中的cellForRowAtIndexPath單擊UITableCell時確定UISwitch的狀態

UISwitch *mySwitch = [[UISwitch alloc]init]; 
self.myNewSwitch = mySwitch; 
[mySwitch release]; 
[cell setAccessoryView: self.myNewSwitch]; 
[(UISwitch *)cell.accessoryView addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventValueChanged]; 

這工作正常使用下面的代碼加載一個表視圖。當我點擊開關時,changeState中的代碼運行良好。

這是我的問題所在。當用戶按下表格中的單元格時,我想查看開關處於何種狀態(開或關)。我的問題是,我無法弄清楚如何確定didSelectRowAtIndexPath代碼。我可以確定正確的單元格,但是當我使用Google進行搜索時,我無法找到如何訪問該單元格上的開關。這裏是我的代碼didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    //If the on/off switch is on, go to the probes page. if off, do not do anything 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    //Determine the switch state here.  
    UISwitch *theSwitch; 
    theSwitch = ??????? //<- What do I do??? 

    if (theSwitch.isOn) { 
     //define the probes view controller 
     Probes *detailViewController = [[Probes alloc] initWithNibName:@"Probes" bundle:nil]; 
     //pass in the ip address 
     detailViewController.lblIPAddr = cell.detailTextLabel.text; 

    // Pass the selected object to the new view controller. 
     [self.navigationController pushViewController:detailViewController animated:YES]; 
     [detailViewController release]; 
    } 
    //Deselect this row 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 

任何幫助/代碼將有所幫助。

-NCGrimbo

回答

1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    //If the on/off switch is on, go to the probes page. if off, do not do anything 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    //Determine the switch state here.   

    UISwitch *theSwitch = (UISwitch *)cell.accessoryView ;  

    if (theSwitch.isOn) { 
     //define the probes view controller 
     Probes *detailViewController = [[Probes alloc] initWithNibName:@"Probes" bundle:nil]; 
     //pass in the ip address 
     detailViewController.lblIPAddr = cell.detailTextLabel.text; 

    // Pass the selected object to the new view controller. 
     [self.navigationController pushViewController:detailViewController animated:YES]; 
     [detailViewController release]; 
    } 
    //Deselect this row 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 
每次做出新的UITableViewCell時間

,但我不知道爲什麼你正在使用,

UISwitch *mySwitch = [[UISwitch alloc]init]; 
self.myNewSwitch = mySwitch; 
[mySwitch release]; 
[cell setAccessoryView: self.myNewSwitch]; 

,self.myNewSwitch是相同UISwitch(最後UiSwitch)。

+0

感謝您的解決方案。它效果很好。至於你問我的問題,這是我另一位開發者展示的方式。如果有更好的方法,請讓我知道。 – NCGrimbo 2011-03-17 14:06:40