Ios 未获取用于在UITableViewCell中点击UISwitch的indexPath
我在一个UITableViewCell中添加了一个UISwitch,表内容是动态的,这意味着在一个tableview中可能有许多UISwitch,我需要获取每个UITableViewCell的UISwitch状态,但不能在Ios 未获取用于在UITableViewCell中点击UISwitch的indexPath,ios,ios5,uitableview,uiswitch,Ios,Ios5,Uitableview,Uiswitch,我在一个UITableViewCell中添加了一个UISwitch,表内容是动态的,这意味着在一个tableview中可能有许多UISwitch,我需要获取每个UITableViewCell的UISwitch状态,但不能在accessoryButtonTappedForRowWithIndexPath方法中获取indexPath 我的代码是: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath
accessoryButtonTappedForRowWithIndexPath
方法中获取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);
}
控制事件应为
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];
}
仍然没有得到索引值我已经更新了我的答案。它没有经过测试。一旦我进入mac电脑,我会很快(几分钟)对它进行测试。是的,它已经过测试,应该会给出预期值。在iOS 7中使用它CGPoint switchPositionPoint=[sender convertPoint:CGPointZero toView:[self tableView]];nsindepath*indepath=[[self tableView]indexPathForRowAtPoint:switchPositionPoint];