用手势轻扫视图

时间:2011-05-04 19:46:22

标签: iphone cocoa-touch uigesturerecognizer gesture

我正在尝试为Iphone开发一个应用程序;但我是新蜜蜂,所以我遇到了很多问题。

我的应用程序有一个默认视图,另一个小视图在主视图中名称为flashcard。

我想添加此视图滑动(或滑动)功能,如Iphone中的照片。例如,如果用户滑动视图直到内部视图的中心到达主视图的边界,则会有两种可能性, 1-如果用户在到达内部视图之前完成滑动将返回到原始位置。 2-如果用户没有停止滑动,内部视图将从滑动方向出现在屏幕上并从相反方向返回屏幕。

所以我在viewDidLoad声明UIPanGestureRecognizer,如下所示

UIPanGestureRecognizer *panFlashCard = [[UIPanGestureRecognizer alloc]
                                       initWithTarget:self action:@selector(handlePanFlashCard:)];

[flashcard addGestureRecognizer:panFlashCard];
[panFlashCard release];

handPanFlashCard行动:

UIView *piece = [recognizer view];
    CGPoint center = piece.center;
    CGFloat x = 160; // the original x axis of inner view

    if ([recognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [recognizer translationInView:piece ];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.55];
        [piece setCenter:CGPointMake(piece.center.x + translation.x, center.y)];
        [UIView commitAnimations];
        CGFloat totalX;
        totalX= x + translation.x;
        if(translation.x <0)
        {            
            if (totalX <= 0)
            {
                [self showNextCard];
            }
            else
            {
                [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.55];
                           [piece setCenter:CGPointMake(self.view.center.x, center.y)];
                           [UIView commitAnimations];
            }
        }
        else
        {
            if (totalX >= self.view.bounds.size.width)
            {
                [self showPreviousCard];
            }
            else
            {
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:0.55];
                [piece setCenter:CGPointMake(self.view.center.x, center.y)];
                [UIView commitAnimations];
            }
        }
    }

showNextCard行动:

[flashcard setCenter:CGPointMake(self.view.bounds.size.width + flashcard.bounds.size.width, flashcard.center.y)]; 

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.55];
    [flashcard setCenter:CGPointMake(self.view.center.x, flashcard.center.y)]; 
    [UIView commitAnimations];

showPreviousCard行动:

  [flashcard setCenter:CGPointMake(0 - flashcard.bounds.size.width, flashcard.center.y)]; 

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.55];
    [flashcard setCenter:CGPointMake(self.view.center.x, flashcard.center.y)]; 
    [UIView commitAnimations];

当我运行这个应用程序时,它会成功构建并运行,但动画有问题,我认为会出现一些错误。

请帮我修正此代码并在滑动时运行流畅的动画。

1 个答案:

答案 0 :(得分:0)

如果我理解你要做什么,那么你可以使用内置控件。查看UIScrollView类上的pagingEnabled属性。还有一个名为PhotoScroller的示例项目可能有所帮助。

http://developer.apple.com/library/ios/#samplecode/PhotoScroller/Introduction/Intro.html