2012-04-04 7 views
3

UITableViewCellにUISwitchを追加しました。テーブルの内容は動的です。つまり、テーブルビューにUISwitchが多数ある可能性があり、すべてのUITableViewCellに対してUISwitch状態を取得する必要があります。 accessoryButtonTappedForRowWithIndexPathメソッドでindexPathを取得できません。UITableViewCellでUISwitchをタップするためのindexPathを取得していない

私のコードは次のとおりです。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    LocationCell *cell = (LocationCell *)[tableView 
              dequeueReusableCellWithIdentifier:@"LocationCell"]; 

    UISwitch *useLocationSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; 
    [cell addSubview:useLocationSwitch]; 
    cell.accessoryView = useLocationSwitch; 

    [useLocationSwitch addTarget: self 
       action: @selector(accessoryButtonTapped:withEvent:) 
    forControlEvents: UIControlEventTouchUpInside]; 

    return cell; 
} 

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event 
{ 
    NSIndexPath * indexPath = [showLocationTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: showLocationTableView]]; 
    if (indexPath == nil) 
     return; 

    [showLocationTableView.delegate tableView: showLocationTableView accessoryButtonTappedForRowWithIndexPath: indexPath]; 
} 

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{ 
    NSLog(@"index path: %@", indexPath.row); 
} 

答えて

5

制御イベントがUIControlEventValueChangedする必要があります。

UIControlEventTouchUpInside。それを変更して、やり直してください。

次のように設定文アクションは次のようになります。

[useLocationSwitch addTarget: self 
         action: @selector(accessoryButtonTapped:withEvent:) 
      forControlEvents: UIControlEventValueChanged]; 

は編集:

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event 
{ 
    UISwitch *switch1 = (UISwitch *)button; 
    UITableViewCell *cell = (UITableViewCell *)switch1.superview; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

    //NSIndexPath * indexPath = [showLocationTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: showLocationTableView]]; 
    if (indexPath == nil) 
     return; 

    [showLocationTableView.delegate tableView: showLocationTableView accessoryButtonTappedForRowWithIndexPath: indexPath]; 
} 
+0

はまだ私は私の答えを更新したインデックス値 – Firdous

+0

を得ていません。そのテストされていません。私はマックマシンに入るとすぐに(数分)テストします。 – Ilanchezhian

+0

はい、テストされており、期待値を与える必要があります。 – Ilanchezhian

関連する問題