iOS抽屉效果开发案例分享

2020-01-14 22:31:39王旭
这篇文章主要为大家分享了iOS抽屉效果开发案例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下  

本文实例为大家分享了iOS抽屉效果开发实例,供大家参考,具体内容如下

在显示在窗口的控制器上添加三个view(如果只需要往一边滑动就只加2个view)

先声明三个view


#import "ViewController.h"
 
@interface ViewController ()
@property(nonatomic, weak) UIView *mainV;
@property(nonatomic, weak) UIView *leftV;
@property(nonatomic, weak) UIView *rightV;
@end

添加view到控制器view上

 


#pragma mark - 添加子控件
- (void)setUpChildViews {
   
  UIView *leftV = [[UIView alloc]initWithFrame:self.view.bounds];
   
  leftV.backgroundColor = [UIColor orangeColor];
   
  [self.view addSubview:leftV];
   
  _leftV = leftV;
   
  UIView *rightV = [[UIView alloc]initWithFrame:self.view.bounds];
   
  rightV.backgroundColor = [UIColor groupTableViewBackgroundColor];
   
  [self.view addSubview:rightV];
   
  _rightV = rightV;
   
  UIView *mainV = [[UIView alloc]initWithFrame:self.view.bounds];
   
  mainV.backgroundColor = [UIColor yellowColor];
   
  [self.view addSubview:mainV];
   
  _mainV = mainV;
}
 
- (void)viewDidLoad {
  [super viewDidLoad];
   
  //添加子控件
  [self setUpChildViews];
   
  //添加Pan手势
  UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
   
  [self.view addGestureRecognizer:pan];
   
  //添加点按手势,在主视图上任意位置点击回到屏幕开始位置
  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
   
  [self.view addGestureRecognizer:tap];
   
}

 


#pragma mark - 手势识别方法
#define targetL -230
#define targetR 200
#define screenW [UIScreen mainScreen].bounds.size.width
- (void)pan:(UIPanGestureRecognizer *)pan {
   
  //获取手势移动的位置
  CGPoint tranP = [pan translationInView:self.view];
   
  //获取x的偏移量
  CGFloat offsetX = tranP.x;
   
  //修改mainV的frame
  _mainV.frame = [self frameWithOffsetX:offsetX];
   
  //判断mainV的x是否大于0
  [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
   
  //复位
  [pan setTranslation:CGPointZero inView:self.view];
   
  //判断当手势结束的时候,定位
  if (pan.state == UIGestureRecognizerStateEnded) {
     
    CGFloat target = 0;
     
    if (_mainV.frame.origin.x > screenW * 0.5) {
      //定位到右边
      target = targetR;
    }else if(CGRectGetMaxX(_mainV.frame) < screenW * 0.5) {
      //定位到左边
      target = targetL;
    }
     
    //获取X轴需要移动的偏移量
    CGFloat offsetX = target - _mainV.frame.origin.x;
     
    [UIView animateWithDuration:0.25 animations:^{
       
      _mainV.frame = target == 0 ? self.view.bounds : [self frameWithOffsetX:offsetX];
 
    }];
     
  }
   
}