最近在做一个贴纸的应用,把贴纸封装成一个sticker的类,并重写了其中的touches begin 和 touches moves方法。贴纸可以拖拽,旋转,缩放。(同时让旋转和缩放同时起作用有点技巧)。
在实现拖拽的时候无论如何在左侧边缘的时候都拖不动,想不到是什么原因。
具体代码如下:
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
self.isOnFirst=YES;
[self.delegatemakeStickerBecomeFirstRespond:self.pasterID] ;
UITouch*touch = [touchesanyObject] ;
touchStart= [touchlocationInView:self.superview] ;
}
- (void)translateUsingTouchLocation:(CGPoint)touchPoint
{
CGPointnewCenter =CGPointMake(self.center.x+ touchPoint.x-touchStart.x,
self.center.y+ touchPoint.y-touchStart.y) ;
self.center= newCenter;
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPointtouch = [[touchesanyObject]locationInView:self.superview];
[selftranslateUsingTouchLocation:touch] ;
touchStart= touch;
}
试了挺久,找到一点苗头是只有左滑的时候才会不行,向上或者向下,向右都没问题。觉得有可能是系统的左滑手势导致。
设置self.navigationController.interactivePopGestureRecognizer.enabled=NO;
果然正常。
关于旋转和缩放手势一起执行的方法,先创建两个手势,实现代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
{
returnYES;
}
手势创建代码如下:
UIPinchGestureRecognizer*pincheGesture = [[UIPinchGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleGesture:)];
pincheGesture.delegate=self;
[selfaddGestureRecognizer:pincheGesture];
UIRotationGestureRecognizer*rotateGesture = [[UIRotationGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleGesture:)] ;
rotateGesture.delegate=self;
[selfaddGestureRecognizer:rotateGesture] ;
手势的方法如下;
- (void)handleGesture:(UIGestureRecognizer*)recognizer
{
//SMImage *selectedImage = [DataCenter sharedDataCenter].selectedImage;
switch(recognizer.state) {
caseUIGestureRecognizerStateBegan:
if(_activeRecognizers.count==0)
self.referenceTransform=self.transform;
[_activeRecognizersaddObject:recognizer];
break;
caseUIGestureRecognizerStateEnded:
self.referenceTransform= [selfapplyRecognizer:recognizertoTransform:self.referenceTransform];
[_activeRecognizersremoveObject:recognizer];
break;
caseUIGestureRecognizerStateChanged: {
CGAffineTransformtransform =self.referenceTransform;
for(UIGestureRecognizer*recognizerin_activeRecognizers)
transform = [selfapplyRecognizer:recognizertoTransform:transform];
self.transform= transform;
break;
}
default:
break;
}
}
分别处理scale和rotate transform即可:
- (CGAffineTransform)applyRecognizer:(UIGestureRecognizer*)recognizer toTransform:(CGAffineTransform)transform
{
if([recognizerrespondsToSelector:@selector(rotation)])
returnCGAffineTransformRotate(transform, [(UIRotationGestureRecognizer*)recognizerrotation]);
elseif([recognizerrespondsToSelector:@selector(scale)]) {
CGFloatscale = [(UIPinchGestureRecognizer*)recognizerscale];
returnCGAffineTransformScale(transform, scale, scale);
}
else
returntransform;
}