【问题标题】:Swipe Gesture between UIView在 UIView 之间滑动手势
【发布时间】:2013-05-06 01:03:24
【问题描述】:

我有一个 ViewController 类,其中我在 self.view 上有一个名为 templateView 的 UIView,它由一个名为 gridView 的 UIView 组成,这里我需要在 templateView 上滑动,为此我添加了类似滑动手势,

swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightAction)];
swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeftAction)];

swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
swipeRight.delegate = self;

swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.delegate = self;

 [templateView addGestureRecognizer:swipeRight];
 [templateView addGestureRecognizer:swipeLeft];

swipeRightswipeLeft 中我需要移动gridView 的左侧和右侧.. 我需要在这些方法中实现什么..?

【问题讨论】:

    标签: ios uiview


    【解决方案1】:

    我建议

    1. 使用带有参数的手势处理程序(以防您曾经向多个视图添加手势);

    2. 确保相关视图已打开userInteractionEnabled

    3. 您不需要设置手势的delegate,除非您正在实现UIGestureRecognizerDelegate 方法之一。

    因此,配置可能如下所示:

    templateView.userInteractionEnabled = YES;
    
    swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [templateView addGestureRecognizer:swipeRight];
    
    swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [templateView addGestureRecognizer:swipeLeft];
    

    然后手势处理程序可能如下所示:

    - (void)handleSwipe:(UISwipeGestureRecognizer *)gesture
    {
        CGRect frame = self.gridView.frame;
    
        // I don't know how far you want to move the grid view.
        // This moves it off screen.
        // Adjust this to move it the appropriate amount for your desired UI
    
        if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
            frame.origin.x += self.view.bounds.size.width;
        else if (gesture.direction == UISwipeGestureRecognizerDirectionLeft)
            frame.origin.x -= self.view.bounds.size.width;
        else
            NSLog(@"Unrecognized swipe direction");
    
        // Now animate the changing of the frame
    
        [UIView animateWithDuration:0.5
                         animations:^{
                             self.gridView.frame = frame;
                         }];
    }
    

    注意,如果您使用自动布局并且视图是由约束而不是translatesAutoresizingMaskIntoConstraints 定义的,那么该处理程序代码必须适当更改。但希望这能给你基本的想法。

    【讨论】:

      【解决方案2】:

      您可以使用一些 UIViewAnimations 来移动 gridView。 创建类似的东西:

      -(void)swipeRightAction{
          [UIView setAnimationDuration:1];
          gridView.frame = CGRectMake(320,0);
          [UIView commitAnimations];
      }
      

      此代码将更改您的 gridView 的框架。您需要根据要滑动视图的位置更改此参数。 我没有尝试代码,请告诉我它是否有效。

      【讨论】: