2012-04-04 67 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