iOS簡易抽屜效果

xmnx 9年前發布 | 5K 次閱讀 Objective-C IOS

直接在controller里面加代碼實現的抽屜效果

@interface ViewController () {
    UIView* _leftView;
}

@end

@implementation ViewController

  • (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.

    _leftView = [[UIView alloc] init]; //把左側邊的view先隱藏 _leftView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height); _leftView.backgroundColor = [UIColor greenColor]; [self.view addSubview:_leftView];

    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; [self.view addGestureRecognizer:pan]; }

  • (void)handlePan:(UIPanGestureRecognizer*) recognizer { CGPoint translation = [recognizer translationInView:self.view]; //增量后的x坐標位置 CGFloat Xresult = translation.x + _leftView.frame.origin.x;

    //向右 if (translation.x >= 0) {

      //leftView已全部拉出,則無法再向右
      if (_leftView.frame.origin.x >= 0 || Xresult >= 0) {
          _leftView.frame = CGRectMake(0, 0, 200, self.view.frame.size.height);
    
          return;
      }
    

    } else if (translation.x < 0) {//向左

      //leftView已全部收回,則無法再向左
      if (_leftView.frame.origin.x <= -200 || Xresult <= -200) {
          _leftView.frame = CGRectMake(-200, 0, 200, self.view.frame.size.height);
          return;
      }
    

    }

    CGRect frame = _leftView.frame; frame.origin.x += translation.x; _leftView.frame = frame;

    //清空移動的距離,這是關鍵 [recognizer setTranslation:CGPointZero inView:recognizer.view];

    //做彈回效果,以中軸為界限 if (recognizer.state == UIGestureRecognizerStateEnded) {

      if (_leftView.frame.origin.x > -100) {
          [self closeView:NO];
      } else {
          [self closeView:YES];
      }
    

    } }

  • (void)closeView:(BOOL)close { if (close) {

      [self moveView:CGRectMake(-200, 0, 200, self.view.frame.size.height)];
    

    } else {

      [self moveView:CGRectMake(0, 0, 200, self.view.frame.size.height)];
    

    } }

  • (void)moveView:(CGRect)frame { [UIView animateWithDuration:0.3 animations:^{

      _leftView.frame = frame;
    

    } completion:^(BOOL finished) {

    }]; }</pre>

 本文由用戶 xmnx 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!