抽屉效果的封装,我一般很少打字,一般我们开发也直接是看代码片段,拿来直接用,我直接把简单封装的抽屉效果demo 项目连接扔上来
其实抽屉是UIView的组装,判断好位置计算好移动时的view的frame 以及通知和定位
核心代码:
#pragma mark - 拖动手势
- (void)pan:(UIPanGestureRecognizer *)pan
{
CGPoint point = [pan translationInView:self.view];
self.mainView.frame = [self frameWithOffsetX:point.x];
// 判断下mainV的x是否大于0
[self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
//复位
[pan setTranslation:CGPointZero inView:self.view];
//判断手势结束位置,做定位
CGFloat target = 0;
if (pan.state == UIGestureRecognizerStateEnded) {
if (self.mainView.frame.origin.x > P_SCREEN_WIDTH / 2) {
target = kTargetR;
}else if (CGRectGetMaxX(self.mainView.frame) < P_SCREEN_WIDTH / 2){
target = kTargetL;
}
CGFloat offsetX = target - self.mainView.frame.origin.x;
[UIView animateWithDuration:0.25 animations:^{
self.mainView.frame = target == 0 ?
self.view.bounds:[self frameWithOffsetX:offsetX];
}];
}
}
#pragma mark - 根据offsetX计算main的frame
- (CGRect)frameWithOffsetX:(CGFloat)offsetX
{
//获取上一次的frame
CGRect frame = self.mainView.frame;
//Y轴偏移
CGFloat offsetY = offsetX * kMaxY / P_SCREEN_HEIGHT;
//获取上次的高度
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;
//获取当前的frame
frame.origin.x += offsetX;
frame.origin.y = (P_SCREEN_HEIGHT - curH) / 2;;
frame.size.height = curH;
frame.size.width = curW;
return frame;
}
#pragma mark - 通知
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if (self.mainView.frame.origin.x >0) {
//往右边移动
self.rightView.hidden = YES;
}else if (self.mainView.frame.origin.x <0){
//往左边移动
self.rightView.hidden = NO;
}
}
点击下面文字下载demo