通过添加边缘手势来实现侧滑的效果,类似于qq界面的边缘侧滑 ,亦或广告界面的侧滑
@interface中定义一个全局view
@property(nonatomic,weak)UIView *adView;添加侧滑手势
// 添加边缘手势 UIScreenEdgePanGestureRecognizer *ges = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(showAd:)]; // 指定左边缘滑动 ges.edges = UIRectEdgeLeft; [self.view addGestureRecognizer:ges]; // 如果ges的手势与collectionView手势都识别的话,指定以下代码,代表是识别传入的手势 [self.collectionView.panGestureRecognizer requireGestureRecognizerToFail:ges];实现滑出方法
- (void)showAd:(UIScreenEdgePanGestureRecognizer *)ges { // 让view跟着手指去移动 // frame的x应该为多少??应该获取到手指的x值 // 取到手势在当前控制器视图中识别的位置 CGPoint p = [ges locationInView:self.view]; NSLog(@"%@", NSStringFromCGPoint(p)); CGRect frame = self.adView.frame; // 更改adView的x值. 手指的位置 - 屏幕宽度 frame.origin.x = p.x - [UIScreen mainScreen].bounds.size.width; // 重新设置上去 self.adView.frame = frame; if (ges.state == UIGestureRecognizerStateEnded || ges.state == UIGestureRecognizerStateCancelled) { // 判断当前广告视图在屏幕上显示是否超过一半 if (CGRectContainsPoint(self.view.frame, self.adView.center)) { // 如果超过,那么完全展示出来 frame.origin.x = 0; }else{ // 如果没有,隐藏 frame.origin.x = -[UIScreen mainScreen].bounds.size.width; } [UIView animateWithDuration:0.25 animations:^{ self.adView.frame = frame; }]; } } /** * 添加滑出的view */ - (void)setupAdView { UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; // 设置背景颜色 view.backgroundColor = [UIColor randomColor]; CGRect frame = view.frame; // 将x值改成负的屏幕宽度,原因是因为默认就在屏幕的左边 frame.origin.x = -view.frame.size.width; // 设置给view view.frame = frame; // 因为该view是盖在所有的view身上,所以应该添加到window上 [[UIApplication sharedApplication].keyWindow addSubview:view]; self.adView = view; // 添加轻扫手势 -- 滑回 UISwipeGestureRecognizer *ges = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(closeAd)]; ges.direction = UISwipeGestureRecognizerDirectionLeft; [self.adView addGestureRecognizer:ges]; }这是回滑的方法
- (void)closeAd { [UIView animateWithDuration:0.25 animations:^{ CGRect frame = self.adView.frame; frame.origin.x = -[UIScreen mainScreen].bounds.size.width; self.adView.frame = frame; }]; }