使用UIScreenEdgePanGestureRecognizer寫iOS7側邊欄
A UIScreenEdgePanGestureRecognizer looks for panning (dragging) gestures that start near an edge of the screen. The system uses screen edge gestures in some cases to initiate view controller transitions. You can use this class to replicate the same gesture behavior for your own actions.
UIScreenEdgePanGestureRecognizer看起來像pan手勢,它是檢測屏幕邊緣的pan手勢的。系統在某些controller轉場的時候會使用這個手勢。你也可以使用這個手勢做其他的事情。
源碼:

#import "RootViewController.h" @interface RootViewController ()<UIGestureRecognizerDelegate> { CGFloat _centerX; CGFloat _centerY; UIView *_backgroundView; } @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; // 存儲坐標 _centerX = self.view.bounds.size.width / 2; _centerY = self.view.bounds.size.height / 2; self.view.backgroundColor = [UIColor blackColor]; // 屏幕邊緣pan手勢(優先級高於其他手勢) UIScreenEdgePanGestureRecognizer *leftEdgeGesture = \ [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftEdgeGesture:)]; leftEdgeGesture.edges = UIRectEdgeLeft; // 屏幕左側邊緣響應 [self.view addGestureRecognizer:leftEdgeGesture]; // 給self.view添加上 // 設置一個UIView用來替換self.view,self.view用來當做背景使用 _backgroundView = [[UIView alloc] initWithFrame:self.view.bounds]; _backgroundView.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_backgroundView]; // 展示的view UIView *showView_01 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)]; showView_01.tag = 0x1; showView_01.backgroundColor = [UIColor redColor]; [_backgroundView addSubview:showView_01]; } - (void)handleLeftEdgeGesture:(UIScreenEdgePanGestureRecognizer *)gesture { // 獲取到當前被觸摸的view UIView *view = [self.view hitTest:[gesture locationInView:gesture.view] withEvent:nil]; NSLog(@"tag = %ld", (long)view.tag); if(UIGestureRecognizerStateBegan == gesture.state || UIGestureRecognizerStateChanged == gesture.state) { // 根據被觸摸手勢的view計算得出坐標值 CGPoint translation = [gesture translationInView:gesture.view]; NSLog(@"%@", NSStringFromCGPoint(translation)); NSLog(@"進行中"); // 進行設置 _backgroundView.center = CGPointMake(_centerX + translation.x, _centerY); } else { // 恢復設置 [UIView animateWithDuration:.3 animations:^{ _backgroundView.center = CGPointMake(_centerX, _centerY); }]; } } @end
處理手勢:
效果如下圖:
如果想與其他手勢並發操作,實現如下代理即可:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}