拖动子视图时阻止UITableViewCell选择

时间:2013-05-02 12:46:59

标签: ios uiview uitableview touches

我有一个UITableViewCell子类,我在其UIView属性中添加了contentView。为了能够拖动该子视图,我实现了UIResponder适当的方法:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [touches anyObject];
  CGPoint currentLocation = [touch locationInView:self.superview];
  if (currentLocation.x >= self.rootFrame.origin.x) {
    return;
  }

  CGRect frame = self.frame;
  frame.origin.x = currentLocation.x;
  self.frame = frame;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  self.frame = self.rootFrame; // rootFrame is a copy of the initial frame
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
 [self touchesEnded:touches withEvent:event];
}

可以毫无问题地拖动子视图,但也会选择单元格,以便调用-tableView:didSelectRowAtIndexPath:

如何在拖动子视图时阻止单元格被选中?

3 个答案:

答案 0 :(得分:0)

-[UITableViewCell setSelectionStyle: UITableViewCellSelectionStyleNone]

当然,仍会调用tableView:didSelectRowAtIndexPath: - 因此您可能希望有选择地忽略回调。

答案 1 :(得分:0)

如果不了解更多信息,就无法确切地说出来,但有几种方法可以实现这一点:

  1. 您可以UITableViewDelegate

  2. 阻止tableView:willSelectRowAtIndexPath:协议中的选择
  3. 您可以将表格置于编辑模式并使用allowsSelectionDuringEditing

  4. 您可以通过覆盖[UITableViewCell setSelected:animated:][UITableViewCell setHighligted:animated:]来阻止选择/突出显示用户界面。仍然会选择单元格。

  5. 您可以禁用默认表格选择并使用您自己的UITapGestureRecognizer(使用[UITableView indexPathForRowAtPoint:]非常简单)。使用自定义识别器,您可以使用其委托来决定您的桌子何时接触。

答案 2 :(得分:0)

为了解决这种情况,我为子视图编写了一个协议:

@protocol MyViewDelegate <NSObject>

///
/// Tells the delegate that touches has begun in view
///
- (void)view:(UIView *)view didBeginDragging:(UIEvent *)event;

///
/// Tells the delegate that touches has finished in view
///
- (void)view:(UIView *)view didFinishDragging:(UIEvent *)event;

@end

然后我在子视图中完成了UIResponder方法,如下所示:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [self.delegate view:self didBeginDragging:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  self.frame = self.rootFrame;
  [self.delegate view:self didFinishDragging:event];
}

最后,我将单元格设置为视图的委托,并在拖动手势正在进行时临时取消单元格选择:

- (void)view:(UIView *)view didBeginDragging:(UIEvent *)event {
  [self setHighlighted:NO animated:NO];
  [self setSelectionStyle:UITableViewCellSelectionStyleNone];
}

- (void)vView:(UIView *)view didFinishDragging:(UIEvent *)event {
  [self setSelectionStyle:UITableViewCellSelectionStyleGray];
}

就是这样

相关问题