如何在没有第三方库的情况下创建自定义幻灯片菜单。

人气:646 发布:2022-10-16 标签: ios objective-c xib

问题描述

我想在我的iOS应用程序中实现滑动菜单,就像抽屉(Andriod)一样。我看了一个教程,但它们都在使用第三方库。是否有可能创建自定义幻灯片菜单。我试图用以下代码创建它,但它只适用于xib文件:

- (IBAction)sidemenu:(id)sender
{
    [UIView animateWithDuration:0.50f animations:^{
        view.frame = self.view.frame;
    } completion:^(BOOL finished) {
        swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(SwipGestureLeftAction:)];
        swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
        [self.view addGestureRecognizer:swipeLeft];
    }];
 }

- (void)SwipGestureAction
{
    UISwipeGestureRecognizer *swiperight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(SwipGestureRightAction:)];
    swiperight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swiperight];
}

#pragma mark AddSwipeGestureLeftAndRight
- (void)SwipGestureRightAction:(UISwipeGestureRecognizer *)swipeRight
{
    [UIView animateWithDuration:0.50f animations:^{
        view.frame = self.view.frame;
    } completion:^(BOOL finished) {
        swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(SwipGestureLeftAction:)];
        swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
        [self.view addGestureRecognizer:swipeLeft];
    }];
}

- (void)SwipGestureLeftAction:(UISwipeGestureRecognizer *)swipeRight
{
    [UIView animateWithDuration:0.50f animations:^{
        [view setFrame:CGRectMake(self.view.frame.origin.x - self.view.frame.size.width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
    } completion:^(BOOL finished){
        [self.view removeGestureRecognizer:swipeLeft];
    }];
}

推荐答案

这是我为您准备的:

我为所有项目中的所有幻灯片菜单创建了一个超类。它管理幻灯片菜单的显示和隐藏,并处理方向更改。它从当前视图的顶部从左侧滑入,并使用暗透明背景部分遮挡了视图的其余部分。 如果您需要其他行为(如推出当前视图),只需覆盖动画部分。 我的幻灯片菜单是单例菜单,因为在我们的应用程序中,每个屏幕上只使用一个幻灯片菜单。

#import <UIKit/UIKit.h>

@interface IS_SlideMenu_View : UIView <UIGestureRecognizerDelegate>
{
    UIView* transparentBgView;
    BOOL hidden;
    int lastOrientation;
}

@property (strong, nonatomic) UIView *menuContainerV;

+ (id)sharedInstance;

- (BOOL)isShown;
- (void)hideSlideMenu;
- (void)showSlideMenu;

@end


#import "IS_SlideMenu_View.h"

@implementation IS_SlideMenu_View

+ (id)sharedInstance
{
    static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[[self class] alloc] init];
    });
    
    return _sharedInstance;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    frame = [[[UIApplication sharedApplication] delegate] window].frame;
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        transparentBgView = [[UIView alloc] initWithFrame:frame];
        [transparentBgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];
        [transparentBgView setAlpha:0];
        transparentBgView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognized:)];
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognized:)];
        [transparentBgView addGestureRecognizer:tap];
        [transparentBgView addGestureRecognizer:pan];
        
        [self addSubview:transparentBgView];
        
        frame.size.width = 280;
        self.menuContainerV = [[UIView alloc] initWithFrame:frame];
        CALayer *l = self.menuContainerV.layer;
        l.shadowColor = [UIColor blackColor].CGColor;
        l.shadowOffset = CGSizeMake(10, 0);
        l.shadowOpacity = 1;
        l.masksToBounds = NO;
        l.shadowRadius = 10;
        self.menuContainerV.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        
        [self addSubview: self.menuContainerV];
        hidden = YES;
    }
    
    //----- SETUP DEVICE ORIENTATION CHANGE NOTIFICATION -----
    UIDevice *device = [UIDevice currentDevice];
    [device beginGeneratingDeviceOrientationNotifications];
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:device];
    
    lastOrientation = [[UIDevice currentDevice] orientation];
    
    return self;
}

//********** ORIENTATION CHANGED **********
- (void)orientationChanged:(NSNotification *)note
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];    
    if(orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight){
        NSLog(@"%ld",orientation);
        if(!hidden && lastOrientation != orientation){
            [self hideSlideMenu];
            hidden = YES;
            lastOrientation = orientation;
        }
    }
}

- (void)showSlideMenu {
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    self.frame = CGRectMake(0, 0, window.frame.size.width, window.frame.size.height);
    
    [self.menuContainerV setTransform:CGAffineTransformMakeTranslation(-window.frame.size.width, 0)];
    
    [window addSubview:self];
//    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    [UIView animateWithDuration:0.5 animations:^{
        [self.menuContainerV setTransform:CGAffineTransformIdentity];
        [transparentBgView setAlpha:1];
    } completion:^(BOOL finished) {
        NSLog(@"Show complete!");
        hidden = NO;
    }];
}

- (void)gestureRecognized:(UIGestureRecognizer *)recognizer
{
    if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]) {
        [self hideSlideMenu];
    } else if ([recognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        static CGFloat startX;
        if (recognizer.state == UIGestureRecognizerStateBegan) {
            startX = [recognizer locationInView:self.window].x;
        } else
        if (recognizer.state == UIGestureRecognizerStateChanged) {
            CGFloat touchLocX = [recognizer locationInView:self.window].x;
            if (touchLocX < startX) {
                [self.menuContainerV setTransform:CGAffineTransformMakeTranslation(touchLocX - startX, 0)];
            }
        } else
        if (recognizer.state == UIGestureRecognizerStateEnded) {
            [self hideSlideMenu];
        }
    }
}

- (void)hideSlideMenu
{
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    window.backgroundColor = [UIColor clearColor];
    [UIView animateWithDuration:0.5 animations:^{
        [self.menuContainerV setTransform:CGAffineTransformMakeTranslation(-self.window.frame.size.width, 0)];
        [transparentBgView setAlpha:0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self.menuContainerV setTransform:CGAffineTransformIdentity];
        
//        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        hidden = YES;
        NSLog(@"Hide complete!");
    }];
}

- (BOOL)isShown
{
    return !hidden;
}

@end

子类只需将子视图添加到menuContainerV视图中并对其进行管理。

示例:

我创建了一个以标题视图和表视图作为其内容的子类。我在XIB中创建了内容视图,XIB的所有者是这个子类。通过这种方式,我可以将插座绑定到XIB。

#import "IS_SlideMenu_View.h"

@interface CC_SlideMenu_View : IS_SlideMenu_View<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView *headerView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

...

@end

当幻灯片菜单实例化时,我加载XIB并将内容视图添加到menuContainerV视图。

#import "CC_SlideMenu_View.h"

@implementation CC_SlideMenu_View

- (instancetype)init
{
    self = [super init];
    if (self) {
        UIView *v = [[[NSBundle mainBundle] loadNibNamed:@"CC_SlideMenu_View" owner:self options:nil] firstObject];
        v.frame = self.menuContainerV.bounds;
        [self.menuContainerV addSubview:v];
        self.tableView.backgroundColor = [UIColor darkGrayColor];
    }
    return self;
}

...

@end

结果类似于this。

547