抽屉的封装

@interface DrawerViewController : UIViewController

// 初始化抽屉leftVC(左边抽屉的视图) mainVC(显示在前面的视图)

- (instancetype)initWithLeftController:(UIViewController *)leftVC mainViewController:(UIViewController *)mainVC;

//打开抽屉

- (void)open;

// 关闭抽屉

- (void)close;

// 切换视图

- (void)setNewMainVC:(UIViewController *)newVC;

@property (nonatomic, assign)BOOL isOpen;

@end    // 以上为.h的属性的声明







// 以下是.m的内容


#import "DrawerViewController.h"

#define  Koffset 0.7

@interface DrawerViewController ()

@property (nonatomic, strong)UIView *leftView;

@property (nonatomic, strong)UIView *mainView;

@property (nonatomic, strong) UIPanGestureRecognizer *pan;

@end

@implementation DrawerViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor whiteColor];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

// 初始化抽屉leftVC(左边抽屉的视图) mainVC(显示在前面的视图)

- (instancetype)initWithLeftController:(UIViewController *)leftVC mainViewController:(UIViewController *)mainVC

{

self = [super init];

if (self) {

[self addChildViewController:leftVC];

[self addChildViewController:mainVC];

[self.view addSubview:leftVC.view];

[self.view addSubview:mainVC.view];

self.leftView = leftVC.view;

self.mainView = mainVC.view;

self.pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panHander:)];

[self.mainView addGestureRecognizer:self.pan];

}

return self;

}

- (void)panHander:(UIPanGestureRecognizer *)sender

{

CGPoint panCenter = [sender translationInView:self.mainView];

CGRect mainFrame = self.mainView.frame;

mainFrame.origin.x += panCenter.x;

if (mainFrame.origin.x >= 0) {

self.mainView.frame = mainFrame;

}

[sender setTranslation:CGPointZero inView:self.mainView];

if (sender.state == UIGestureRecognizerStateEnded) {

if (self.mainView.frame.origin.x > screenWidth *Koffset / 2) {

[self open];

}else {

[self close];

}

}

}

//打开抽屉

- (void)open;

{

CGRect mainFrame = self.mainView.frame;

mainFrame.origin.x = screenWidth *Koffset;

[UIView animateWithDuration:0.3 animations:^{

self.mainView.frame = mainFrame;

self.leftView.userInteractionEnabled = NO;

} completion:^(BOOL finished) {

self.isOpen = YES;

self.leftView.userInteractionEnabled = YES;

}];

}

// 关闭抽屉

- (void)close

{

[UIView animateWithDuration:0.3 animations:^{

self.mainView.frame = self.view.frame;

self.leftView.userInteractionEnabled = NO;

} completion:^(BOOL finished) {

self.isOpen = NO;

self.leftView.userInteractionEnabled = YES;

}];

}

// 切换视图

- (void)setNewMainVC:(UIViewController *)newVC

{

//    if ([self.childViewControllers containsObject:newVC]) {

//        [self addChildViewController:newVC];

//    }

newVC.view.frame = self.mainView.frame;

[self.view addSubview:newVC.view];

[self.mainView removeFromSuperview];

self.mainView = newVC.view;

}

你可能感兴趣的:(抽屉的封装)