UIView:如何检查触摸是否在它们开始的同一视图内结束

ma1*_*w28 8 uiview uitouch three20 touchesbegan

AcaniUsers,我已经创建了一个ThumbView : UIView实例网格UITableView.所有thumbViews都有宽度kThumbSize.如何检测触摸是否在它们开始的同一视图内结束?

erg*_*cak 9

在您使用的视图扩展中;

斯威夫特 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
}
Run Code Online (Sandbox Code Playgroud)


ma1*_*w28 3

以下方法有效,但我不确定这是否是最好的方法。我也这么认为。

由于所有的thumbViews宽度均为kThumbSize,只需检查实例的touchesEndedx 坐标(假设)是否小于或等于。这意味着触摸在 内结束。无需检查 y 坐标,因为如果触摸垂直移动,则包含、 的 滚动且触摸被取消。locationInViewUITouchself.multipleTouchEnabled = NOkThumbSizethumbViewtableViewthumbViews

ThumbView : UIView在(其实例是 a 的子视图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];
    }
}
Run Code Online (Sandbox Code Playgroud)

要一次只注册一个触摸thumbView,您可能还需要self.exclusiveTouch = YES;init的实例方法中进行设置ThumbView

  • 您可以通过这样做来编写更好的代码:“if (CGRectContainsPoint(self.bounds, touchPoint)) { ... }”。:) (2认同)