一个简单的抽屉效果,简单实用!
整体思路:
主要是在控制器的View上添加了两个View,一个左侧leftView和一个mainView,给mainView添加手势,动画效果,根据计算判断偏移量的X值是否大于leftView的宽度的一半;
iOS中抽屉效果的封装
#import "XBViewController.h"
#define SWIDTH [UIScreen mainScreen].bounds.size.width
@interface XBViewController ()
/**自定义View */
@property (strong, nonatomic) UIView *mainV;
@property (nonatomic ,weak) UIView *leftV;
@end
@implementation XBViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 添加界面
[self setView];
//创建手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
// 添加手势
[self.mainV addGestureRecognizer:pan];
//添加点按手势,点击时关闭
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(close)];
[self.leftV addGestureRecognizer:tap];
}
- (void)close
{
[UIView animateWithDuration:1.5 animations:^{
self.mainV.transform = CGAffineTransformIdentity;
self.mainV.frame = self.view.bounds;
}];
}
#define tartgetR SWIDTH * 0.8
// 实现手势方法
- (void)pan:(UIPanGestureRecognizer *)pan
{
//获取偏移量(是相对于最原始的点,起点的偏移量)
CGPoint tranP = [pan translationInView:_mainV];
//计算当前MainV的位置,大小
[self positionWithOffset:tranP.x];
//判断手势的状态
if (pan.state == UIGestureRecognizerStateEnded) {
if (self.mainV.frame.origin.x > SWIDTH * 0.5) {
[UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
// 自动定位到右侧
CGFloat offset = tartgetR - self.mainV.frame.origin.x;
[self positionWithOffset:offset];
} completion:nil];
}else{
[self close];
}
}
// 把偏移量做一次复位,清0(不让偏移量进行累加)
[pan setTranslation:CGPointZero inView:self.mainV];
}
// 计算偏移量
#define maxScale 0.3
- (void)positionWithOffset:(CGFloat)offset {
//获取Frame
CGRect frame = self.mainV.frame;
frame.origin.x += offset;
self.mainV.frame = frame;
//只能往右边拖动
if (frame.origin.x<=0) {
self.mainV.frame = [UIScreen mainScreen].bounds;
}
//最大值是多少
// 什么时候为最大
CGFloat scale = frame.origin.x * maxScale / SWIDTH;
// 计算缩放比例
scale = 1 - scale;
if (scale >= 1) {
scale = 1;
}
// 缩放
self.mainV.transform = CGAffineTransformMakeScale(scale, scale);
}
#pragma mark - 添加View
- (void)setView
{
// 添加左边的View
UIView *leftV = [[UIView alloc]initWithFrame:self.view.bounds];
leftV.backgroundColor = [UIColor blueColor];
[self.view addSubview:leftV];
//mainV
UIView *mainV = [[UIView alloc]initWithFrame:self.view.bounds];
mainV.backgroundColor = [UIColor redColor];
[self.view addSubview:mainV];
self.mainV = mainV;
}
@end
效果图:
图片弹出缩放.gif
网友评论