【问题标题】:Not getting indexPath for tapping UISwitch in a UITableViewCell没有在 UITableViewCell 中点击 UISwitch 的 indexPath
【发布时间】:2012-04-04 10:42:06
【问题描述】:

我在一个UITableViewCell中添加了一个UISwitch,表格内容是动态的,这意味着一个tableview中可能有很多UISwitches,我需要获取每个UITableViewCell的UISwitch状态,但没有得到@987654322中的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);
}

【问题讨论】:

    标签: ios ios5 uitableview uiswitch


    【解决方案1】:

    控制事件应该是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]]; NSIndexPath *indexPath = [[self tableView] indexPathForRowAtPoint:switchPositionPoint];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多