簡體   English   中英

拖動子視圖時阻止UITableViewCell選擇

[英]Prevent UITableViewCell selection when dragging a subview

我有一個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:

如何在拖動子視圖時防止單元格被選中?

-[UITableViewCell setSelectionStyle: UITableViewCellSelectionStyleNone]

當然,仍然會調用tableView:didSelectRowAtIndexPath:因此您可能要有選擇地忽略回調。

在不了解更多信息的情況下不可能准確地說出,但是有幾種方法可以實現:

  1. 您可以通過tableView:willSelectRowAtIndexPath:來阻止UITableViewDelegate協議中的選擇tableView:willSelectRowAtIndexPath:

  2. 您可以將表格置於編輯模式並使用allowsSelectionDuringEditing

  3. 您可以通過覆蓋[UITableViewCell setSelected:animated:][UITableViewCell setHighligted:animated:]來阻止選擇/突出顯示UI。 雖然仍將選擇該單元格。

  4. 您可以禁用默認表選擇並使用自己的UITapGestureRecognizer (通過使用[UITableView indexPathForRowAtPoint:]非常容易)。 使用自定義識別器,您可以使用其委托來決定您的表何時獲得觸摸。

為了解決這種情況,我為子視圖編寫了一個協議:

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

而已

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM