关于导航栏的返回按钮,单击退回上一页,长按退回到顶层的控制器

QQ音乐如果长按返回按钮就会有如题的效果,实现起来很简单,直接替换掉系统的返回按钮就可以了

1.重写pushViewController方法

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if (self.childViewControllers.count) { // 隐藏底部栏
        viewController.hidesBottomBarWhenPushed = YES;
        UIBarButtonItem *leftBtn = [UIBarButtonItem itemWithImageName:@"navback_black" target:self action:@selector(back) press:@selector(popToRootVC)];

        viewController.navigationItem.leftBarButtonItem = leftBtn;
        // 如果自定义返回按钮后, 滑动返回可能失效, 需要添加下面的代码
        __weak typeof(viewController)Weakself = viewController;
        self.interactivePopGestureRecognizer.delegate = (id)Weakself;
    }

    [super pushViewController:viewController animated:animated];
}

2.返回操作

//普通返回
- (void)back
{
    // 判断两种情况: push 和 present
    if ((self.presentedViewController || self.presentingViewController) && self.childViewControllers.count == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else
        [self popViewControllerAnimated:YES];
}
//长按返回顶层
- (void)popToRootVC{
    [self popToRootViewControllerAnimated:YES];
}

3.创建可以点按和长按的UIBarButtonItem

+ (instancetype)itemWithImageName:(NSString *)imageName target:(id)target action:(SEL)action press:(SEL)press{
    UIButton *button = [[UIButton alloc] init];
    //设置不同状态的image
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_highlighted",imageName]] forState:UIControlStateHighlighted];
    //根据图片大小设置当前button的大小
    button.size = button.currentImage.size;
    
    //添加点击事件
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:target action:press];
    longPress.minimumPressDuration = 0.8;
    [button addGestureRecognizer:longPress];
    
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

你可能感兴趣的:(关于导航栏的返回按钮,单击退回上一页,长按退回到顶层的控制器)