ios开发——实用技术OC-Swift篇&触摸与手势识别
iOS开发学习之触摸事件和手势识别
- 触摸事件
- 手势识别
- 手机摇晃
- typedef NS_ENUM(NSInteger, UIEventType){
- UIEventTypeTouches,
- UIEventTypeMotion,
- UIEventRemoteControl,
- };
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸开始");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸移动Touch对象个数:%d",[touches count]);
// 要移动界面上黄颜色的视图
// 1. 得到当前手指的位置
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
// 2. 得到上一次手指的位置
CGPoint preLocation = [touch previousLocationInView:self.view];
// 3. 计算两个位置之间的偏移
CGPoint offset = CGPointMake(location.x - preLocation.x, location.y - preLocation.y);
// 4. 使用计算出来的偏移量,调整视图的位置
[_demoView setCenter:CGPointMake(_demoView.center.x + offset.x, _demoView.center.y + offset.y)];
// 完整的UITouch事件调试方法
NSLog(@"触摸移动");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
#pragma mark 触摸结束
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// 完整的UITouch事件调试方法
NSLog(@"触摸完成");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
#pragma mark 触摸中断
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
// 完整的UITouch事件调试方法
NSLog(@"触摸中断");
for (UITouch *touch in touches) {
NSLog(@"%@", touch);
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
println("touchesBegan")
//获取touches数量
let numTouches = touches.count
//获取点击屏幕的次数
let tapTouches = (touches as NSSet).anyObject()?.tapCount
//获取事件发生时间
let timestamp = event.timestamp
//获取当前相对于self.view的坐标
let locationPoint = (touches as NSSet).anyObject()?.locationInView(self.view)
//获取上一次相对于self.view的坐标
let previousPoint = (touches as NSSet).anyObject()?.previousLocationInView(self.view)
//允许使用手势
self.view.userInteractionEnabled = true
//支持多点触摸
self.view.multipleTouchEnabled = true
println("\(tapTouches)")
//判断如果有两个触摸点
{
//获取触摸集合
let twoTouches = (touches as NSSet).allObjects
//获取触摸数组
let first:UITouch = twoTouches[] as! UITouch //第1个触摸点
let second:UITouch = twoTouches[]as! UITouch //第2个触摸点
//获取第1个点相对于self.view的坐标
let firstPoint:CGPoint = first.locationInView(self.view)
//获取第1个点相对于self.view的坐标
let secondPoint:CGPoint = second.locationInView(self.view)
//计算两点之间的距离
let deltaX = secondPoint.x - firstPoint.x;
let deltaY = secondPoint.y - firstPoint.y;
let initialDistance = sqrt(deltaX*deltaX + deltaY*deltaY )
println("两点间距离是:\(initialDistance)")
}
}
//手指在移动
// override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
//2015年5月2后修改
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
println("touchesMoved")
}
//触摸结束
// override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
//2015年5月2后修改
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
println("touchesEnded")
}
//触摸意外终止
//模拟器演示:鼠标拖动的同时,按键盘command+shift+h 相当于点击手机home键,退出应用,触发touchesCancelled事件,在打电话、等情况下也会触发
// override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
//2015年5月2后修改
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
println("touchesCancelled")
}
- state——手势状态view——手势发生视图
- (void)viewDidLoad
{
[super viewDidLoad];
// 根据实例化方法,我们知道:
// 1.有一个处理消息的对象,应该是self
// 2.我们需要定义一个方法,当手势识别检测到的时候,运行
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
// setNumberOfTapsRequired 点按次数
[tap setNumberOfTapsRequired:];
// setNumberOfTouchesRequired 点按的手指数量
[tap setNumberOfTouchesRequired:];
// 把手势识别增加到视图上
[self.demoView addGestureRecognizer:tap];
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchAction:)];
[self.demoView addGestureRecognizer:pinch];
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotationAction:)];
[self.demoView addGestureRecognizer:rotation];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
[self.demoView addGestureRecognizer:pan];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
[self.demoView addGestureRecognizer:longPress];
// 向左扫
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.view addGestureRecognizer:swipeLeft];
// 向右扫
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
[self.view addGestureRecognizer:swipeRight];
// 向上扫
UISwipeGestureRecognizer *swipeTop = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
[swipeTop setDirection:UISwipeGestureRecognizerDirectionUp];
[self.view addGestureRecognizer:swipeTop];
// 向下扫
UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
[swipeDown setDirection:UISwipeGestureRecognizerDirectionDown];
[self.view addGestureRecognizer:swipeDown];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)swipeAction:(UISwipeGestureRecognizer *)sender
{
NSLog(@"%d", sender.direction);
switch (sender.direction) {
case UISwipeGestureRecognizerDirectionLeft:
NSLog(@"向左扫");
break;
case UISwipeGestureRecognizerDirectionRight:
NSLog(@"向右扫");
break;
case UISwipeGestureRecognizerDirectionUp:
NSLog(@"向上扫");
break;
case UISwipeGestureRecognizerDirectionDown:
NSLog(@"向下扫");
break;
default:
break;
}
}
- (void)longPressAction:(UILongPressGestureRecognizer *)sender
{
// 我们可以利用demoView的Tag属性,默认时tag=0
// 如果tag=0,我们放大一倍,否则,我们缩小一半
CGFloat scale;
) {
scale = 2.0;
_demoView.tag = ;
} else {
scale = 0.5;
_demoView.tag = ;
}
sender.view.transform = CGAffineTransformScale(sender.view.transform, scale, scale);
}
- (void)panAction:(UIPanGestureRecognizer *)sender
{
// 在拖放手势中是需要考虑手指的状态的UIGestureRecognizerState
// 在拖放手势中使用的状态是UIGestureRecognizerStateChanged
// 通常在使用拖放手势的时候,当手指离开的时候,应该做一个很小的动作,提醒用户拖放完成
if (sender.state == UIGestureRecognizerStateChanged) {
// locationInView
[_demoView setCenter:[sender locationInView:self.view]];
} else if (sender.state == UIGestureRecognizerStateEnded) {
[_demoView setBackgroundColor:[UIColor yellowColor]];
}
}
- (void)rotationAction:(UIRotationGestureRecognizer *)sender
{
sender.view.transform = CGAffineTransformRotate(sender.view.transform, sender.rotation);
// 和捏合操作类似,旋转角度同样需要方福伟
sender.rotation = 0.0f;
}
#pragma mark - 捏合手势
- (void)pinchAction:(UIPinchGestureRecognizer *)sender
{
// 有关转换的内容,我们在后续动画部分再继续
sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale);
// 缩放功能很简单,但是不要忘记将比例复位
sender.scale = 1.0f;
NSLog(@"捏我了");
}
#pragma mark - 点按手势
- (void)tapAction:(UITapGestureRecognizer *)sender
{
NSLog(@"点我了 %@", sender);
}
#pragma mark - 手势触摸事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸事件!");
// 1. 先取出UITouch对象
// 2. 判断响应点击的UIView是不是我们需要的
UITouch *touch = [touches anyObject];
if ([touch view] == _imageView) {
NSLog(@"点到图像了!");
}
}
Swift:
添加手势
//点击事件
var atap = UITapGestureRecognizer(target: self, action: "tapDo:")
self.view.addGestureRecognizer(atap)
atap.numberOfTapsRequired = //单击次数
atap.numberOfTouchesRequired = //手指个数
//拖动事件
var aPan = UIPanGestureRecognizer(target: self, action: "handlenPan:")
self.view.addGestureRecognizer(aPan)
aPan.minimumNumberOfTouches = //最少手指个数
aPan.maximumNumberOfTouches = //最多手指个数
//长按事件
var aLongPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
self.view.addGestureRecognizer(aLongPress)
aLongPress.minimumPressDuration = //需要长按的时间,最小0.5s
//捏合事件
var aPinch = UIPinchGestureRecognizer(target: self, action: "pinchDo:")
self.view.addGestureRecognizer(aPinch)
//旋转事件
var aRotation = UIRotationGestureRecognizer(target: self, action: "rotatePiece:")
self.view.addGestureRecognizer(aRotation)
//轻扫事件--左轻扫
var leftSwipe = UISwipeGestureRecognizer(target: self, action: "leftSwipe:")
self.view.addGestureRecognizer(leftSwipe)
leftSwipe.direction = UISwipeGestureRecognizerDirection.Left
//轻扫事件--右轻扫
var rightSwipe = UISwipeGestureRecognizer(target: self, action: "rightSwipe:")
self.view.addGestureRecognizer(rightSwipe)
rightSwipe.direction = UISwipeGestureRecognizerDirection.Right
//轻扫事件--上轻扫
var upSwipe = UISwipeGestureRecognizer(target: self, action: "upSwipe:")
self.view.addGestureRecognizer(upSwipe)
upSwipe.direction = UISwipeGestureRecognizerDirection.Up
//轻扫事件--下轻扫
var downSwipe = UISwipeGestureRecognizer(target: self, action: "downSwipe:")
self.view.addGestureRecognizer(downSwipe)
downSwipe.direction = UISwipeGestureRecognizerDirection.Down
}
实现
//手势
//点击事件
func tapDo(sender:UITapGestureRecognizer)
{
println("点击事件")
}
//拖动事件
func handlenPan(sender:UIPanGestureRecognizer)
{
println("拖动事件")
if sender.state == .Began
{
//拖动开始
}
else if sender.state == .Changed
{
//拖动过程
}
else if sender.state == .Ended
{
//拖动结束
}
}
//长摁事件
func longPress(sender:UILongPressGestureRecognizer)
{
println("长摁事件")
}
//捏合事件
func pinchDo(sender:UIPinchGestureRecognizer)
{
println("捏合")
}
//旋转事件
func rotatePiece(sender:UIRotationGestureRecognizer)
{
println("旋转")
}
//轻扫事件--左轻扫
func leftSwipe(sender:UISwipeGestureRecognizer)
{
println("左轻扫")
}
//轻扫事件--右轻扫
func rightSwipe(sender:UISwipeGestureRecognizer)
{
println("右轻扫")
}
//轻扫事件--上轻扫
func upSwipe(sender:UISwipeGestureRecognizer)
{
println("上轻扫")
}
//轻扫事件--下轻扫
func downSwipe(sender:UISwipeGestureRecognizer)
{
println("下轻扫")
}
. 新建摇晃监听视图ShakeListenerView,并且设置canBecomeFirstResponder返回YES
- (BOOL)canBecomeFirstResponder
{
return YES;
}
. 在Storyboard中将ViewController的View的Class设置为:ShakeListenerView
. 在ViewController.m文件中增加:viewDidAppear和viewDidDisappear在视图出现和消失时成为/撤销第一响应者身份
. 在视图控制器中增加手势监听方法:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.subtype == UIEventSubtypeMotionShake) {
NSLog(@"shake phone");
}
}
#pragma mark - 要让ViewController支持摇晃,需要写三个方法
// 1. 成为第一响应者,视图一出现时,就应该成为第一响应者
- (void)viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
// 不要忘记去实现父类方法
[super viewDidAppear:animated];
}
// 2. 注销第一响应者,视图要关闭的时候,注销
- (void)viewDidDisappear:(BOOL)animated
{
[self.view resignFirstResponder];
// 不要忘记去实现父类方法
[super viewDidDisappear:animated];
}
// 3. 监听并处理移动事件,判断是否摇晃了手机
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake) {
NSLog(@"摇啊摇,摇到外婆桥!!!");
}
}
ios开发——实用技术OC-Swift篇&触摸与手势识别的更多相关文章
- ios开发——实用技术总结Swift篇&swift常用开发技术总结
swift常用开发技术总结 懒加载:属性,数组(字典),控件... 数组(懒加载): lazy var shops:Array<Dictionary<String, String>& ...
- iOS开发——实用技术OC篇&单例模式的实实现(ACR&MRC)
单例模式的实实现(ACR&MRC) 在iOS开发中单例模式是一种非常常见的模式,虽然我们自己实现的比较少,但是,系统却提供了不少的到来模式给我们用,比如最常见的UIApplication,No ...
- iOS开发——实用技术OC篇&事件处理详解
事件处理详解 一:事件处理 事件处理常见属性: 事件类型 @property(nonatomic,readonly) UIEventType type; @property(nonatomic ...
- ios开发——实用技术篇Swift篇&多点触摸与手势识别
多点触摸与手势识别 //点击事件 var atap = UITapGestureRecognizer(target: self, action: "tapDo:") self.vi ...
- iOS开发——技术精华Swift篇&Swift 2.0和Objective-C2.0混编之第三方框架的使用
swift 语言是苹果公司在2014年的WWDC大会上发布的全新的编程语言.Swift语言继承了C语言以及Objective-C的特性,且克服了C语言的兼容性问题.Swift语言采用安全编程模式,且引 ...
- iOS开发——新特性Swift篇&Swift 2.0 异常处理
Swift 2.0 异常处理 WWDC 2015 宣布了新的 Swift 2.0. 这次重大更新给 Swift 提供了新的异常处理方法.这篇文章会主要围绕这个方面进行讨论. 如何建造异常类型? 在 i ...
- ios开发——实用技术OC-Swift篇&本地通知与远程通知详解
本地通知与远程通知详解 一:本地通知 Local Notification的作用 Local Notification(本地通知) :是根据本机状态做出的通知行为,因此,凡是仅需依赖本机状态即可判 ...
- iOS开发——实用技术OC篇&简单抽屉效果的实现
简单抽屉效果的实现 就目前大部分App来说基本上都有关于抽屉效果的实现,比如QQ/微信等.所以,今天我们就来简单的实现一下.当然如果你想你的效果更好或者是封装成一个到哪里都能用的工具类,那就还需要下一 ...
- iOS开发——混编Swift篇&OC移植为swift
将Ojective-C代码移植转换为Swift代码 2015-03-09 15:07发布:yuhang浏览:201 相比于Objective-C,Swift语言更加简练.有时我们需要把原来写的一些 ...
随机推荐
- Gentoo安装
Gentoo Linux安装详解--根据官方WiKi整理 时间:2014-06-26 06:37:54 阅读:549 评论:0 收藏:0 [点我收藏+] 标签: ...
- POJ 3436 ACM Computer Factory (拆点+输出解)
[题意]每台计算机由P个零件组成,工厂里有n台机器,每台机器针对P个零件有不同的输入输出规格,现在给出每台机器每小时的产量,问如何建立流水线(连接各机器)使得每小时生产的计算机最多. 网络流的建图真的 ...
- Mint Linuxubuntu 字体配置文件
<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fon ...
- ORACLE SQLloader详细语法
Oracle SQL Loader的详细语法 SQL*LOADER是ORACLE的数据加载工具,通常用来将操作系统文件迁移到ORACLE数据库中.SQL*LOADER是大型数据 ...
- 树莓pi快速ssh【校园网】
校园网是NAT后的,没有显示器,我把路由器的DHCP服务关了,这样的情况下怎么ssh到树莓pi? 把树莓pi 连到路由器上(已经关闭DHCP),手机安装FING https://play.google ...
- iOS7适配之设计篇
(注:文章简要翻译自 Apple <iOS 7 UI Transition Guide>,由于该文档为开发者预览版,并非最终文档,所以 iOS7 正式上线可能有部分不同) 准备工作 iOS ...
- Android UI -- 布局介绍(布局包括FrameLayout, LinearLayout, RelativeLayout, GridLayout)
首先介绍常用布局类 FrameLayout 最简单的布局管理器. 这个布局管理类有几个特性: 添加组件默认在左上角的. 如果添加多个组件会叠加到一起,并且都在左上角.(可以通过一gravity属性改变 ...
- 把之前写的几个项目放到了github上
之前有的源码放在我的电脑里不知道什么时候就没了,满满都是回忆啊,怪可惜的. https://github.com/redclock/Adv-Game:一个java游戏 https://github.c ...
- IOS成长之路-调用照相机和相册功能
打开相机: //先设定sourceType为相机,然后判断相机是否可用(ipod)没相机,不可用将sourceType设定为相片库 UIImagePickerControllerSourceType ...
- Keil µVision4 中出现中文乱码的解决办法
首先得说一下,以前都没有遇到过类似的问题,但是看到有个同学曾经满篇的乱码那叫个心疼. 这里我所说的办法其实只是格式转换的问题,对于其他原因造成的,可能会在以后遇到的时候再来处理了.另外,在将代码文件转 ...