??觸摸是iOS的交互核心鸠匀,他不簡(jiǎn)單局限于“按下按鈕”或“點(diǎn)擊鍵盤”,還包括手勢(shì)識(shí)別在內(nèi)的一系列手勢(shì)逾柿;
觸摸#
??觸摸包含以下信息:
- 發(fā)生的地方
- 處在哪個(gè)階段(按下缀棍,移動(dòng),抬起)
- 點(diǎn)擊次數(shù)
- 時(shí)間
??每個(gè)觸摸操作及其信息都保存在UITouch對(duì)象里面机错,而這樣一組UITouch對(duì)象則放在UIEvert對(duì)象里面?zhèn)鬟f爬范。
觸摸的五個(gè)階段:
UITouchPhaseBegan---開始觸碰
UITouchPhaseMoved---移動(dòng)
UITouchPhaseStationary---從上個(gè)事件后仍在觸碰但未移動(dòng)
UITouchPhaseEnded---結(jié)束觸碰
UITouchPhaseCancelled--不在追蹤觸碰
UIResponder類中的觸摸事件響應(yīng) - touchesBagan: withEvent: --當(dāng)開始觸碰屏幕,系統(tǒng)會(huì)調(diào)用這個(gè)方法
- touchesMoved: withEvent:--當(dāng)觸摸屏幕并持續(xù)移動(dòng)時(shí)弱匪,系統(tǒng)會(huì)調(diào)用此方法
- touchesEnded: withEvent:--觸摸過(guò)程結(jié)束調(diào)用此方法
- touchesCancelled: withEvent:--觸摸阻斷青瀑,系統(tǒng)調(diào)用方法
??這些方法通常需要UIView或者UIViewController來(lái)實(shí)現(xiàn),相當(dāng)于復(fù)寫父類的方法萧诫。對(duì)視圖的觸摸涉及到響應(yīng)鏈狱窘,這里有興趣的朋友可以查查相關(guān)響應(yīng)規(guī)則。
??另外iOS支出單點(diǎn)觸摸(Single-Touch)和多點(diǎn)觸摸(Multi-Touch)财搁;
手勢(shì)識(shí)別器#
??這是蘋果公司提供的一種強(qiáng)大的識(shí)別方式蘸炸;你懂的!
iOS SDK內(nèi)置的幾種手勢(shì)
- 點(diǎn)擊(tap)--一根或多個(gè)手指觸碰尖奔;可以通過(guò)gestureRecongnizers屬性來(lái)設(shè)定想要的點(diǎn)擊次數(shù)
- 滑動(dòng)(swipe)--上下左右所作出的短距離單點(diǎn)觸碰或者多點(diǎn)觸碰搭儒,這種手勢(shì)注意的是不能太超出主方向
- 雙指聚攏(pinch)--擠壓或拉伸
- 旋轉(zhuǎn)(rotate)--兩個(gè)手指順時(shí)針或者逆時(shí)針移動(dòng),識(shí)別器會(huì)返回吧旋轉(zhuǎn)的角度和速度返回給開發(fā)者
- 拖動(dòng)(pan)--拿手指在屏幕上作出拖拽的 動(dòng)作提茁,這里會(huì)識(shí)別到坐標(biāo)的變化
- 長(zhǎng)按(long press)--這個(gè)不解釋
?下面我們用代碼演示如何用觸碰和手勢(shì)識(shí)別器分別實(shí)現(xiàn)拖拽功能:
@implementation DragView
{
CGPoint startLocation;
}
-(instancetype)initWithImage:(UIImage *)anImage
{
self=[super initWithImage:anImage];
if(self)
{
self.userInteractionEnabled=YES;
}
return self;
}
-(void)touchBegan:(NSSet *)touches withEvent:(UIEvent *)event{
startLocation =[[touches anyObject] locationInView:self];
[self.superview bringSubviewToFront:self];//讓觸摸的視圖顯示在屏幕最前方
}
-(void)touchMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPiont pt=[[touches anyObject] locationInView:self];
float dx=pt.x-startLocation.x;
float dy=pt.y-startLocation.y;
CGPiont newcenter=CGPonitMake(
self.center.x+dx,self.center.y+dy);
self.center=newcenter;
}
?用手勢(shì)識(shí)別器實(shí)現(xiàn)
@implementation DragView
{
CGPoint spreviousLocation;
}
-(instancetype)initWithImage:(UIImage *)anImage
{
self=[super initWithImage:anImage];
if(self)
{
self.userInteractionEnabled=YES;
UIPanGestureRecongnizer *panGesture=[[UIPanGestureRecongnizer alloc]initWithTarget:self action: @selector(handlePan:)];
self.gestureRecognizers=@[panGesture];
}
return self;
}
-(void)touchBegan:(NSSet *)touches withEvent:(UIEvent *)event{
spreviousLocation =self.center;
[self.superview bringSubviewToFront:self];//讓觸摸的視圖顯示在屏幕最前方
}
-(void)hanlePan:(UIPanGestureRecongnizer *)sender{
CGPoint tanslation=[sender translationInView:self,superview];
self.center=CGPonitMake(spreviousLocation.x+tanslation.x,spreviousLocation.y+tanslation.y);
}