一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

iOS触摸事件的使用详解

时间:2015-11-01 编辑:简简单单 来源:一聚教程网

触摸事件在iOS中是最常用的事件,这里我们来介绍下触摸事件。

在下面的例子中定义UIImageView。首先我们在TouchEventViewController中添加触摸事件,并利用触摸移动事件来移动Image,具体代码如下:

@implementation TouchEvenViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView * _image=[[KCImage alloc]initWithFrame:CGRectMake(50, 50, 150, 169)];
    [_image setImage:[UIImage imageName:@"zmit"]];
    [self.view addSubview:_image];
}
 
#pragma mark - 视图控制器的触摸事件
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"开始触摸");
}
 
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得一个触摸对象(对于多点触摸可能有多个对象)
    UITouch *touch=[touches anyObject];
    //取得当前位置
    CGPoint current=[touch locationInView:self.view];
    //取得前一个位置
    CGPoint previous=[touch previousLocationInView:self.view];
    //移动前的中点位置
    CGPoint center=_image.center;
    //移动偏移量
    CGPoint offset=CGPointMake(current.x-previous.x, current.y-previous.y);
    
    //重新设置新位置
    _image.center=CGPointMake(center.x+offset.x, center.y+offset.y);
    
    NSLog(@触摸中");
 
}
 
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"触摸结束");
}
@end
一个简单的拖动的触摸事件,在这里展示给大家了。

热门栏目