2012-04-04 65 views
3

我在UITableViewCell中添加了UISwitch,表格内容是动态的,这意味着在tableview中可能有很多UISwitch,我需要为每个UITableViewCell获取UISwitch状态,但没有得到accessoryButtonTappedForRowWithIndexPath方法中的indexPath没有获取IndexPath在UITableViewCell中点击UISwitch

我的代码是:

- (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 2012-04-04 10:51:38

+0

我已经更新我的答案。它没有测试。一旦我进入mac机器,我会很快测试它(几分钟)。 – Ilanchezhian 2012-04-04 10:59:31

+0

是的,它被测试,应该给予预期的价值。 – Ilanchezhian 2012-04-04 11:05:32