事件触发的类型
摇:(摇晃手机换歌)
摇的三种状态
(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"摇一摇开始");
self.view.backgroundColor = [UIColorcolorWithRed:arc4random() %256 / 255.0green:arc4random() %256 / 255.0blue:arc4random() %256 / 255.0alpha:0.5];
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"摇一摇结束");
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"摇一摇被取消");
}
2).触摸(最重要)*****
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸开始");
[self.myTextField resignFirstResponder];//点空白处回收键盘
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸移动");
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸结束");
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸被取消");
}
让View随着鼠标箭头移动
(1)创建一个类继承于UIView, 在其.m文件里进行下述的步骤
(1).补上延展部分.位置移动
@interfaceMyView ()
(2).定义属性用来记录视图的开始的坐标.位置移动
@property(nonatomic,assign)CGPoint starPoiont;
@end
@implementation MyView
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
触碰一下改变背景颜色
(1).设置随机颜色
self.backgroundColor = [UIColorcolorWithRed:arc4random() %256 / 255.0green:arc4random() %256 / 255.0blue:arc4random() %256 / 255.0alpha:0.5];
集合里的元素个数.位置移动
NSLog(@"%ld", touches.count);//运行之后的到的结果是1
(3).集合里有一个触摸类的对象.位置移动
UITouch *touch = [touchesanyObject];
(4).通过触摸对象获取相应视图的当前位置.位置移动
self.starPoiont = [touchlocationInView:self];
NSLog(@"%g , %g ",self.starPoiont.x,self.starPoiont.y);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
(5).通过移动,找到变化,然后让MyView也进行相应的调整,从而实现视图随鼠标移动的效果.位置移动
(6).获取触摸的对象.位置移动
UITouch *touch = [touchesanyObject];
(7).获取移动之后的坐标.位置移动
CGPoint movePoint = [touchlocationInView:self];
(8).坐标的变化(末位置 -初位置).位置移动
CGFloat dx = movePoint.x -self.starPoiont.x;
CGFloat dy = movePoint.y -self.starPoiont.y;
(9).设置视图的移动变化(将View的中心坐标 + 移动变化量).位置移动
self.center =CGPointMake(self.center.x + dx,self.center.y +dy);
}