[英]How to control the transition between 2 UIView states using a swipe gesture?
[英]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];
在swipeRight
和swipeLeft
我需要移動gridView
左側和右側。我需要這些方法來實現什么..?
我建議
使用帶參數的手勢處理程序(如果您將手勢添加到多個視圖中);
確保有問題的視圖已打開userInteractionEnabled
。
除非您正在實現其中一個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.