您的位置:首页 > 产品设计 > UI/UE

UI之touchEvent

2015-12-14 09:47 435 查看
用背景色的随机改变来验证touchEvent的效果

#import <UIKit/UIKit.h>

//引入头文件

#import "mainViewController.h"

@interface MangoTouchView : UIView

@end

#import "MangoTouchView.h"

@interface MangoTouchView ()

{

CGPoint _point;

UIView *_view;

}

@end

@implementation MangoTouchView

//重写init方法

- (instancetype)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

[self loadingCustomView];

}

return self;

}

- (void)loadingCustomView{

self.backgroundColor = [UIColor cyanColor];

_view = [[UIView alloc]initWithFrame:CGRectMake(40, 130, 100, 40)];

_view.backgroundColor = [UIColor lightGrayColor];

[self addSubview:_view];

}

//触摸事件

//当点击到屏幕上时触发

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

//NSLog(@"%s",__FUNCTION__);

// 从触摸手势集合中取出任意触摸点

UITouch *touch = [touches anyObject];

//通过触摸点在当前视图上的位置,返回触摸点的坐标

_point = [touch locationInView:_view];

// NSLog(@"%@",NSStringFromCGPoint(_point));

}

//当手指在屏幕上移动时就会调用

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

//NSLog(@"%s",__FUNCTION__);

}

//当手指离开屏幕时触发

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

//NSLog(@"%s",__FUNCTION__);

//把当前view设置为随机色,arc4random()%256值的区间(0~255),(0~255)/255计算出的是0.0到1.0区间的数

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

// UITouch *end = [touches anyObject];

// CGPoint endp = [end locationInView:self];

// NSLog(@"%@",NSStringFromCGPoint(endp));

UITouch *touch = [touches anyObject];

CGPoint movepoint = [touch locationInView:_view];

CGFloat offsetX = movepoint.x - _point.x;

CGFloat offsetY = movepoint.y - _point.y;

_view.center = CGPointMake(_view.center.x+offsetX, _view.center.y+offsetY);

}

//当来电话(上拉控制中心的时候)或者其他系统级别的事件(上拉控制中心的时候)打断时触发

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

NSLog(@"%s",__FUNCTION__);

}

#import <UIKit/UIKit.h>

@interface mainViewController : UIViewController

@end

#import "mainViewController.h"

//引入头文件

#import "MangoTouchView.h"

@interface mainViewController ()

@end

@implementation mainViewController

//重写loadingView方法,加载当前视图控制器自带的view

- (void)loadView{

// 调用父类的初始化方法

[super loadView];

// 用自定义的view覆盖自带view(self.view)

self.view = [[MangoTouchView alloc]initWithFrame:self.view.frame];

}

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor orangeColor];

//创建mangoView,设置其跟self.view一样大

MangoTouchView *mango = [[MangoTouchView alloc]initWithFrame:self.view.frame];

//添加到根视图上

[self.view addSubview:mango];

//释放

[mango release];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: