事件处理

在操作手机时,经常会有各种操作,在iOS中,就会用事件来处理这些操作(应该叫响应)。

UIEvent,事件,就是硬件捕捉一个用户的操作设备的对象。

iOS事件分为三类:触摸事件,晃动事件,远程控制事件

触摸事件:用户通过触摸屏幕触摸设备操作对象,输入数据。

实现触摸,就是iOS的UIView继承于UIResponder,支持多点触摸。所以,只要继承于UIview的所有视图,都可以响应触摸方法。

 

触摸处理,其实就是实现几个方法即可。

 

开始触摸:

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

在开始触摸屏幕时,就会执行这个方法,因此,想要在触摸屏幕时,实现一些功能,或者提示,都可以在这个方法里添加。

NSSet集合里放着对象,就是UITouch对象。对象里包含这个触摸事件的情况,包括所在的window的frame,所在的视图的frame,所在window的位置,所在视图的位置等等。

event包含了这次触摸事件的事件。包括触摸事件的类型(开始触摸?触摸移动?)以及触摸所在的哪个window,哪个view和所在window和view的位置。

触摸移动:

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

在屏幕上滑动时,就是会执行这个方法。

touches和event与开始触摸方法一样的意思。

触摸结束:

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

触摸事件结束所掉方法。

取消触摸:

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

取消触摸所调方法。

 

一个例子:

让一个视图,随着触摸移动而移动:

NewView.m

这个视图是我们自己定义的视图。也就是视图控制器控制的子视图。由于AppDelegate和ViewController与前面的写法一样,就不写出来了。

#import "NewView.h"

#import "MyView.h"

 

@interface NewView ()

// 保存起始点

@property(nonatomic,assign)CGPoint point;

// 保存开始frame的点

@property(nonatomic,assign)CGPoint framepoint;

 

@end

 

@implementation NewView

 

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

    }

    return self;

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    

UITouch *touch =  [touches anyObject];

    // 保存手指第一次触碰位置

    self.point = [touch locationInView:self.superview];

    // frame的第一次位置

    self.framepoint = self.frame.origin;

    NSLog(@"%@",NSStringFromCGPoint(self.point));

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch =  [touches anyObject];

    CGPoint movepoint = [touch locationInView:self.superview];

    CGFloat detailX = movepoint.x - self.point.x;

    CGFloat detailY = movepoint.y - self.point.y;

   

    self.frame = CGRectMake(self.framepoint.x+detailX, self.framepoint.y+detailY, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));

    self.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];

    NSLog(@"%@",NSStringFromCGPoint(self.point));

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

}

 

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

 

}

@end

posted @   Coder_J  阅读(153)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
点击右上角即可分享
微信分享提示