簡體   English   中英

在UIView之間滑動手勢

[英]Swipe Gesture between UIView

我有一個ViewController類,我在self.view上有一個名為templateView的UIView,它包含一個名為gridView的UIView,這里我需要在templateView上滑動,因為我已經添加了swipegesture,

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左側和右側。我需要這些方法來實現什么..?

我建議

  1. 使用帶參數的手勢處理程序(如果您將手勢添加到多個視圖中);

  2. 確保有問題的視圖已打開userInteractionEnabled

  3. 除非您正在實現其中一個UIGestureRecognizerDelegate方法,否則無需設置手勢的delegate

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

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定義的,則此處理程序代碼必須適當更改。 但希望這能為您提供基本的想法。

您可以使用一些UIViewAnimations移動gridView。 創建類似的東西:

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

此代碼將更改gridView的框架。 您需要根據要滑動視圖的位置更改此參數。 我沒有嘗試代碼,讓我知道它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM