觸摸事件01
這篇文章講一些觸摸事件的基本知識和兩個簡單的案例供參考
1. 移動uiview
2. 根據(jù)移動繪制星星
移動UIview的案例
可識別的三類輸入事件
- 觸摸事件
- 運(yùn)動(加速計)事件
- 遠(yuǎn)程控制事件
觸摸事件:指的是單點(diǎn)和多點(diǎn)觸摸事件
運(yùn)動(加速計):例如微信的搖一搖事件
遠(yuǎn)程控制:例如耳機(jī)線空歌曲(播放,暫停)
響應(yīng)者對象
在ios開發(fā)中并不是所有的對象都能處理觸摸事件,只有繼承了UIResponder的對象才能處理和接收觸摸事件。我們稱之為響應(yīng)者對象
四個不同的方法處理觸摸事件
touchesBegin、touchesMoved 、touchesEnd、touchesCanceled(這四個方法都有 touches和event參數(shù))
- touchesBegin:觸摸時間開始
- touchesMoves:觸摸事件的移動事件
- tocuhesEnd:觸摸事件的結(jié)束事件
- touchesCanceled:觸摸事件被取消,比如正在觸摸時電話打進(jìn)來,此時觸摸會被取消。
UITouch類中包含的兩個成員函數(shù):
*- (CGPoint) locationInView:(UIView *)view 針對view的坐標(biāo)系
*-(CGPoint) previousLocationInView:(UIView *)view 記錄前一個坐標(biāo)
實(shí)現(xiàn)效果

最終效果
主要代碼
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchesMoves%@",touches);
//1.從nsset中去除uitouch對象
//取出集合的一個對象,通常實(shí)在單點(diǎn)觸摸時
UITouch *touch = [touches anyObject];
//2.知道手指觸摸的位置
CGPoint location = [touch locationInView:self.view];
//2.1 對位置進(jìn)行修正 使用previousLocationInView對位置進(jìn)行修正
CGPoint plocation = [touch previousLocationInView:self.view];
CGPoint deltaP = CGPointMake(location.x - plocation.x, location.y-plocation.y);
//3.設(shè)置紅色視圖的位置
CGPoint newCenter = CGPointMake(self.redView.center.x +deltaP.x, self.redView.center.y+deltaP.y);
[self.redView setCenter:newCenter];
}
中間的修正部分為 防止 第一次移動時的跳動問題,算出相對的專心點(diǎn)
第二個繪制軌跡的案例
實(shí)現(xiàn)效果

多點(diǎn)觸控和繪制軌跡
這個案例主要是多點(diǎn)觸控
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSInteger i = 0;
//遍歷touches集合 來添加圖像
for (UITouch *touch in touches) {
UIImageView * imageView = [[UIImageView alloc]initWithImage:self.images[i]];
CGPoint location = [touch locationInView:self.view];
[imageView setCenter:location];
[self.view addSubview:imageView];
[UIView animateWithDuration:2.0f animations:^{
[imageView setAlpha:0.5f];
}completion:^(BOOL finished) {
[imageView removeFromSuperview];
}];
i++;
}
NSLog(@"%@",touches);
}
謝謝........
write by Seven