2

我有一个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:被调用。

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

4

3 回答 3

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];
}

而已

于 2013-05-03T10:43:46.560 回答
0
-[UITableViewCell setSelectionStyle: UITableViewCellSelectionStyleNone]

当然,tableView:didSelectRowAtIndexPath:仍然会被调用——所以你可能想有选择地忽略回调。

于 2013-05-02T13:00:18.480 回答
0

在不了解更多信息的情况下无法准确判断,但有几种方法可以实现这一点:

  1. 您可以通过以下方式阻止UITableViewDelegate协议中的选择tableView:willSelectRowAtIndexPath:

  2. 您可以将表格置于编辑模式并使用allowsSelectionDuringEditing

  3. 您可以通过覆盖[UITableViewCell setSelected:animated:]或来阻止选择/突出显示 UI [UITableViewCell setHighligted:animated:]。但仍会选择该单元格。

  4. 您可以禁用默认表选择并使用您自己的UITapGestureRecognizer(使用 非常容易[UITableView indexPathForRowAtPoint:])。使用自定义识别器,您可以使用它的委托来决定您的表格何时收到触摸。

于 2013-05-02T13:18:19.850 回答