【问题标题】:How to detect finger moves in or out my customized UIView如何检测手指移入或移出我的自定义 UIView
【发布时间】:2013-12-17 08:18:42
【问题描述】:
我有一个自定义的 UIView
@interface EColumn : UIView
我在它的超级视图中有很多这个 EColumn 的实例。
如何检测手指何时按住并在此 UIView 区域内移动,以及何时移出。
我不是指点击手势,我可以使用这个来检测点击手势:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(taped:)];
[self addGestureRecognizer:tapGesture];
【问题讨论】:
标签:
ios
iphone
objective-c
uiview
uigesturerecognizer
【解决方案1】:
@implementation EColumn
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UIView *view = [self touchedViewWithTouches:touches andEvent:event];
NSLog(@"%@",view);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UIView *view = [self touchedViewWithTouches:touches andEvent:event];
NSLog(@"%@",view);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UIView *view = [self touchedViewWithTouches:touches andEvent:event];
NSLog(@"%@",view);
}
- (UIView *)touchedViewWithTouches:(NSSet *)touches andEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];
UIView *touchedView;
for (UIView *view in self.subviews)
{
if(CGRectContainsPoint(view.frame, touchLocation))
{
touchedView = view;
break;
}
}
return touchedView;
}
@end
【解决方案2】:
您可以使用 UILongPressGestureRecognizer 检测特定时间的手指按住。为此,您还可以指定 minimumPressDuration 和 numberOfTouchesRequired
UILongPressGestureRecognizer *longPressRecognizer =
[[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:@selector(longPressDetected:)];
longPressRecognizer.minimumPressDuration = 3;
longPressRecognizer.numberOfTouchesRequired = 1;
[self addGestureRecognizer:longPressRecognizer];
要检测移动,您可以使用 UIPanGestureRecognizer
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[self addGestureRecognizer:panRecognizer];