2011-07-12 10 views
0

Iこれと同じコードを使用して、TableViewの行にスイッチを追加します。 スイッチが変更されると、switchChangedが呼び出されます。しかし、実際に変更された行(どのスイッチ)にアクセスするにはどうすればよいですか?あなたは、スイッチを追加しているUITableViewのUISwitchの行へのアクセス

- (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); 

}

答えて

2

UITableViewCellオブジェクトはswitchControl.superviewので

UITableViewCell * cell = (UITableViewCell *)switchControl.superview; 
NSIndexPath * indexPath = [self.tableView indexPathForCell:cell]; 
+0

になりますありがとうございました!作品は完璧! – Erika

関連する問題