iOS抽屉效果开发案例分享

2020-01-14 22:31:39王旭

 


- (void)tap {
   
  [UIView animateWithDuration:0.25 animations:^{
    _mainV.frame = self.view.bounds;
  }];
   
}

#define kMaxY 80
#pragma mark - 根据offsetX计算mainV的frame
- (CGRect)frameWithOffsetX:(CGFloat)offsetX {
   
  //获取上一次的frame
  CGRect frame = _mainV.frame;
   
  //获取屏幕的高度
  CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
   
  //获取屏幕的宽度
  //CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
   
  //X轴平移一点对应Y轴需要平移的距离
  CGFloat offsetY = offsetX * kMaxY / screenW;
   
  //获取上一次的高度
  CGFloat preH = frame.size.height;
   
  //获取上一次的宽度
  CGFloat preW = frame.size.width;
   
  //获取当前高度
  CGFloat curH = preH - 2 * offsetY;
  //如果是向左滑动
  if(frame.origin.x < 0) {
    curH = preH + 2 * offsetY;
  }
   
  //获取尺寸的缩放比例
  CGFloat scale = curH / preH;
   
  //获取当前宽度
  CGFloat curW = preW * scale;
   
  //获取当前x
  frame.origin.x += offsetX;
   
  //获取当前y
  CGFloat y = (screenH - curH) / 2;
  frame.origin.y = y;
   
  frame.size.width = curW;
  frame.size.height = curH;
   
  return frame;
   
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
   
  if(_mainV.frame.origin.x > 0) {//往右边滑动
    _rightV.hidden = YES;
  }else if(_mainV.frame.origin.x < 0) {//往左边滑动
    _rightV.hidden = NO;
  }
   
}

如果想要在mainV主视图中显示tableView,就新创建一个TableViewController,在这里面显示tableView的数据,


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
  return 30;
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
   
  static NSString *ID = @"cell";
   
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
   
  if(cell == nil) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
  }
   
  cell.textLabel.text = [NSString stringWithFormat:@"第%ld行", indexPath.row];
   
  return cell;
}

再创建一个在storyboard中显示的控制器XXMainViewController,继承自实现了抽屉效果的ViewController,并且在storyboard中将class改为这个控制的类名,还要将显示tableView的控制成为他的子控制器


- (void)viewDidLoad {
  [super viewDidLoad];
   
  XXViewController *vc = [[XXViewController alloc]init];
  vc.view.frame = self.view.bounds;
   
  //让vc成为主视图控制器的子控制器
  [self addChildViewController:vc];
   
  //主视图展示tableView
  [self.mainV addSubview:vc.view];
   
}