UIView/Drawer 使用平移/滑动手势
Posted
技术标签:
【中文标题】UIView/Drawer 使用平移/滑动手势【英文标题】:UIView/Drawer using Pan/Swipe Gesture 【发布时间】:2016-08-10 11:19:34 【问题描述】:我正在尝试在滑动/平移手势上打开和关闭UIView
,我从以下链接中找到了一些帮助
Link,和我想做的很接近。
我希望 UIView
默认打开 100 像素,用户可以使用手势滑动/平移 UIView
直到父 UIViewController
的 75% 并回到 100 像素,但它在下面的代码中闪烁。我希望UIView
的X
位置为0
,这样它就可以像从顶部打开的抽屉一样。
- (void)viewDidLoad
[super viewDidLoad];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
drawerView = [self.storyboard instantiateViewControllerWithIdentifier:@"drawerVC"];
[drawerView.view setFrame:CGRectMake(0, -self.view.frame.size.height + 100, self.view.frame.size.width, self.view.frame.size.height * 0.75)];
[drawerView.view setBackgroundColor:[UIColor redColor]];
[drawerView.view addGestureRecognizer:panGesture];
-(void)move:(UIPanGestureRecognizer*)recognizer
recognizer.view.center = CGPointMake(self.view.frame.size.width/2,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded)
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
float slideFactor = 0.1 * slideMult; // Increase for more of a slide
CGPoint finalPoint = CGPointMake(0,
recognizer.view.center.y + (velocity.y * slideFactor));
finalPoint.x = 0;
finalPoint.y = MIN(MAX(finalPoint.y, 0), drawerView.view.frame.size.height*.75);
if (fabs(recognizer.view.frame.origin.y) >= fabs(yOffset))
return;
NSLog(@"ended %f",finalPoint.y);
if (finalPoint.y < recognizer.view.frame.size.height/2)
// [self movePanelToOriginalPosition];
else
[self movePanelToCenterPosition];
-(void)movePanelToCenterPosition
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^
drawerView.view.frame = CGRectMake(0, 0, drawerView.view.frame.size.width, drawerView.view.frame.size.height);
completion:^(BOOL finished)
// Stuff to do
];
如果 UIView 处于默认状态(100 像素)并且只能向下滑动到所需的 CGPoint
,是否有任何东西可以阻止用户在顶部(向上)方向平移 UIView
。
【问题讨论】:
【参考方案1】:在你的移动中:检查移动是否开始或正在进行的方法
else if (recognizer.state == UIGestureRecognizerStateBegin || Recognizer.state == UIGestureRecognizerStateChanged)" 并且在 if 视图中处于其极限。如果是这样,您可以禁用/重新启用手势识别器。这将取消平移.. .
- (void) move:(UIGestureRecognizer *)sender
if(sender.state == UIGestureRecognizerStateBegan || sender.state == UIGestureRecognizerStateChanged)
BOOL shouldEnablePan = NO; // TODO: do some logic here to figure out if you want to allow pan
if(!shouldEnablePan && [sender isKindOfClass:[UIPanGestureRecognizer class]])
sender.enabled = NO;
sender.enabled = YES;
else ...
【讨论】:
以上是关于UIView/Drawer 使用平移/滑动手势的主要内容,如果未能解决你的问题,请参考以下文章