您的位置:首页 > 移动开发 > IOS开发

iOS中实现视图的拖动

2015-07-16 08:57 561 查看
因为 UIView支持触摸时间,(uiview继承于UIResponder),而支持多点触摸
需要定义UIView的子类,实现触摸相关的方法.

触摸相关的方法有

/**
触摸开始时经过的事件
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
/**
* 触摸滑动时处理的事件
*
*/

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
/**
* 滑动停止事件
*
*/

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
/**
* 滑动取消的事件
*/

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

实现一个uiview的滑动
和我们学得控制器指定自定义VIEW一样.
在这里先复习一下
1:首先创建一个控制器MainViewController
在该控制器的.h文件中声明一个uiview类型的属性.@property(nonatomic,retain)UIView *Rview;
在该控制器的.m文件重写loadView方法.
映入 #import "RootView.h"
- (void)loadView
{
self.Rview = [[RootView alloc] initWithFrame:[UIScreen mainScreen].bounds];

self.view =self.Rview;

}

2:在appdelegate.m文件中设置启动页面
首先引入#import “MainViewController.h"
MainViewController *mvc = [[MainViewController alloc] init];

self.window.rootViewController =mvc;
3:添加一个uiview为RootView
在该uiview中的.m文件中 把我们要移动的uiview添加到该uiview中来
首先引入#import "ResponderVie.h"
在该uiview的初始化方法中添加
ResponderVie *resp = [[ResponderVie alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];


[self addSubview:resp];
---------------------------------------------------------------------------------------
4:创建一个滑动页面
ResponderVie继承自uiview
首先在该uiview的.h文件中声明两个CGPoint方法
/**
* 记录起始位置
*/
@property(nonatomic,assign)CGPoint startPont;

/**
* 记录当前位置
*/

@property(nonatomic,assign)CGPoint currtPoint;

其次在该uiview的.m文件中添加滑动事件

/**
触摸开始时经过的事件
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
/**
* 触摸滑动时处理的事件
*
*/

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
/**
* 滑动停止事件
*
*/

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
/**
* 滑动取消的事件
*/

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
4.1首先我们在touchesBegan事件中获取起始位置的坐标方法如下

UITouch *touchs = [touches anyObject];
CGpoint startP = [touchs locationInView:self]//去得自相对于自己的坐标

//记录起始的位置
self.startPoint = startP;

4.2 最主要的处理就是在touchesMoved事件中,他时滑动事件会记录全程滑动过程.

//记录当前坐标
UITouch *touc = [touches anyObject];
CGPoint movePoint = [touc locationInView:self];
self.currtPoint = movePoint;

//计算偏移量
CGFloat dx = self.currtPoint.x - self.startPont.x;
CGFloat dy = self.currtPoint.y - self.startPont.y

//每次累加计数
CGPoint center = self.center;
center.x += dx;
center.y += dy;
self.center = center;
4.3 如果要记录是不是左出了上下左右的移动,我们就要在touchesEnded事件里处理咯
在次不做详细介绍
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: