现在的触屏手机越来越多,当然,手势的使用也是一个不可避免的话题.今天我们就来学习几个手势.
上一篇我们讲到了 touch began,move,end,cancel 的 实现.我们今天就着重说说手势吧.
先看看我们的storeBoard 的控件介绍.我们就是添加了三个label(先说成三个),和 一个更新label的事件.
最后一个label 是关于我们的轻扫屏幕的显示的.
#import <UIKit/UIKit.h>
@interface BIDViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UILabel *tapsLabel;
@property (weak, nonatomic) IBOutlet UILabel *toucheslabel;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property CGPoint gestureStartPoint;
-(void)updateLabelFromtouches:(NSSet *)touches;
-(void)updateLabelFromtouches:(NSSet *)touches
{
NSInteger numTaps = [[touches anyObject] tapCount];//点击了几次屏幕?
NSString *tapsMessage = [[NSString alloc]initWithFormat:@"%d taps detected",numTaps ];
tapsLabel.text = tapsMessage;
NSUInteger numTouches = [touches count]; //用了几根手指?
NSString *touchMessage = [[NSString alloc]initWithFormat:@"%d touches detectes detected.",numTouches ];
toucheslabel.text = touchMessage;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
messageLabel.text = @"touches Began";
[self updateLabelFromtouches:touches];
//UITouch *touch = [touches anyObject];
//gestureStartPoint = [touch locationInView:self.view];
得到触摸的UITouch对象.然后确定该点击的位置.
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
messageLabel.text = @"touchesMoved";
[self updateLabelFromtouches:touches];
// UITouch *touch = [touches anyObject];
// CGPoint currentPosition = [touch locationInView:self.view];
得到当前的最新位置.
//下面的代码判断 move的长短.
CGFloat deltaX = fabsf(gestureStartPoint.x - currentPosition.x);
CGFloat deltaY = fabsf(gestureStartPoint.y - currentPosition.y);
if(deltaX >=kMinimunGestureLength && deltaY <= kMaxnumVariance)
{
label.text = @"水平滑动";
[self performSelector:@selector(eraseText) withObject:nil afterDelay:2];
}
else if(deltaY >=kMinimunGestureLength && deltaX <= kMaxnumVariance)
{
label.text = @"竖直滑动";
[self performSelector:@selector(eraseText) withObject:nil afterDelay:2];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
messageLabel.text = @"ttouchesEnded";
[self updateLabelFromtouches:touches];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
messageLabel.text = @"touchesCancelled";
[self updateLabelFromtouches:touches];
}
我们现在看到的是 点击,滑动 和离开的 事件触发.
把我注释的代码去掉 你就可以体验 上下左右滑动了~