UIView:如何检查触摸是否在同一视图中结束,开始的位置?

8
AcaniUsers 中,我在 UITableView 内创建了一个由 ThumbView : UIView 实例组成的网格。所有的 thumbViews 的宽度都是 kThumbSize。如何检测触摸事件是否在同一个视图内开始和结束?
2个回答

9
在视图扩展中,您使用的是:
Swift 4:
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    guard let touchPoint = touches.first?.location(in: self) else { return }
    guard self.bounds.contains(touchPoint) else { return }
    // Do items for successful touch inside the view
}

3
以下方法可行,但不确定是否是最佳实践。我认为是的。
由于所有的thumbViews都有一个宽度为kThumbSize,因此在touchesEnded中只需检查UITouch实例的locationInView的x坐标(假设self.multipleTouchEnabled = NO)是否小于或等于kThumbSize即可。这意味着触摸结束在thumbView内部。无需检查y坐标,因为如果触摸垂直移动,包含thumbViews的tableView会滚动并取消触摸。
在ThumbView:UIView中进行以下操作(其实例是UITableView的子视图):
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesEnded %@", touches);
    CGPoint touchPoint = [[touches anyObject] /* only one */ locationInView:self];
    if (touchPoint.x >= 0.0f && touchPoint.x <= kThumbSize) {
        [(ThumbsTableViewCell *)self.superview.superview thumbTouched:self];
    }
}

为了只在一个thumbView上注册触摸,您还可能希望在ThumbViewinit实例方法中设置self.exclusiveTouch = YES;

2
你可以通过这样做来编写更好的代码:if (CGRectContainsPoint(self.bounds, touchPoint)) { ... }。 :) - BastiBen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接