平移手势离开UIView时会延迟动画,并进行去抖动?

时间:2013-08-07 05:15:00

标签: objective-c cocoa-touch

是否有一种或两种惯用方法来处理下面描述的UI交互?也许不需要自定义类?

我正在iPadd应用程序中实现拖放操作,并希望处理dropppable上没有释放拖动并且平移手势离开UIView的情况。

  • 当draggable在其上方时,视图会展开并获取边框,并且当可拖动区域离开时,它将返回到先前的大小并丢失边框。在缩小动画开始之前会有明显的延迟。
  • 在缩小动画开始之前,可拖动的区域可能会被带回区域,这表明需要某种debouncing,即收集在一段时间内发生的事件并将它们视为一个事件。
  • 我知道在平移手势期间会触发大量事件,我不想分配不必要的资源(例如,计时器)。

我正在考虑使用一个自定义计时器,可能是these lines,但也许有更简单的事情呢?

1 个答案:

答案 0 :(得分:0)

每当手指在视图上移动时,以下代码将使用300毫秒的充气动画为视图充气,并且只要触摸在外面,视图就会使视图缩小回正常状态。没有panGestureRecognizerRequired。

@interface CustomView : UIView
{
    BOOL hasExpanded;
    CGRect initialFrame;
    CGRect inflatedFrame;
}
@end

@implementation CustomView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        hasExpanded = NO;

        initialFrame = frame;

        CGFloat inflateIncrement = 50.0f;

        inflatedFrame = CGRectMake(self.frame.origin.x-(inflateIncrement*0.5f),
                                        self.frame.origin.y-(inflateIncrement*0.5f),
                                        self.frame.size.width+inflateIncrement,
                                        self.frame.size.height+inflateIncrement);

    }
    return self;
}


-(void)forceDeflate
{
    if (hasExpanded)
    {
        //start deflating view animation
        [UIView animateWithDuration:0.3 animations:^{
            self.frame = initialFrame;

        }];
        hasExpanded = NO;
    }
}


-(void)inflateByCheckingPoint:(CGPoint)touchPoint
{
    if(!hasExpanded)
    {
        if(CGRectContainsPoint(self.frame,touchPoint))
        {
            //start inflating view animation
            [UIView animateWithDuration:0.3 animations:^{
                self.frame = inflatedFrame;

            }];

            hasExpanded = YES;
        }

    }
    else
    {
        if(!CGRectContainsPoint(self.frame,touchPoint))
        {
            //start deflating view animation
            [UIView animateWithDuration:0.3 animations:^{
                self.frame = initialFrame;

            }];

            hasExpanded = NO;
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *singleTouch = [touches anyObject];
    CGPoint touchPoint = [singleTouch locationInView:self.superview];
    [self inflateByCheckingPoint:touchPoint];
}

-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *singleTouch = [touches anyObject];
    CGPoint touchPoint = [singleTouch locationInView:self.superview];
    [self inflateByCheckingPoint:touchPoint];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self forceDeflate];
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self forceDeflate];
}

@end