iOS中实现视图的拖动

本文介绍了如何在iOS开发中实现视图的拖动功能。通过创建UIView的子类并重写触摸事件方法,包括touchesBegan、touchesMoved、touchesEnded和touchesCancelled,详细阐述了记录起始位置、处理滑动过程以及更新视图中心点的过程,从而实现视图的平滑移动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为 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事件里处理咯

在次不做详细介绍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值