美文网首页iOS相关记录本
iOS 点击tabbar的一个item,直接push新页面,而不

iOS 点击tabbar的一个item,直接push新页面,而不

作者: iOS_July | 来源:发表于2019-04-13 11:09 被阅读0次

需求是这样:
我底部有三个tabbar的item,假如我现在停留在第一个item对应页面上,此时点击中间的item,实现直接push到一个页面,返回后,页面还是第一个item对应的页面,第一个item依然是选中状态。

  • 实现效果图:


    效果图.gif
第一步,代理
  • 在你自定义的BaseTabBarController中,遵守代理<UITabBarControllerDelegate,UITabBarDelegate>
  • 千万记得self.delegate = self;
  • 代码:
#pragma mark - 实现中间item点击直接push的需求
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    
    if ([tabBarController.tabBar.selectedItem.title isEqualToString:@"消息中心"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:[NSString stringWithFormat:@"%@%ld",kNotificationMessagePush,tabTag] object:nil];
//        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMessagePush object:nil];
        return NO;
        
    }
    return YES;
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    //这里为什么要通过item名字来判断第几个tab呢?
    //因为发现self.selectIndex不准确,索性手动来判断。
    //解释下为什么需要知道当前是第几个item?
    //因为SB创建的tabbarController没有navgation,所以无法直接push跳转。
    //present虽然能跳转,但是没了navgation,在present的页面万一push就又麻烦了。所以不能直接在tabbarController里面push;
    //另外,为了保证发送通知针对的是你当前所在的界面,而不是每次点击发送的通知和接收的通知都一样,所以,加上index后缀,使得通知一一对应。

    
    if ([item.title isEqualToString:@"工作台"]) {
        tabTag = 0;
    }
    if ([item.title isEqualToString:@"个人中心"]) {
        tabTag = 2;
    }
    if ([item.title isEqualToString:@"消息中心"]) {
        return;
    }
}
第二步,实现通知
  • 利用通知,进行直接push的效果
  • 除开我的目标item对应的VC里,去接收通知(为什么:因为,我的需求是点击第二个item,直接push,也就是说,我其实是在第一个item或者第二个item对应页面上做的push,所以要除开目标item)
  • 代码:
#pragma mark - 通知相关
- (void)notificationCenterConfig{
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(justPush:) name:kNotificationMessagePush object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(justPush:) name:[NSString stringWithFormat:@"%@2",kNotificationMessagePush] object:nil];
}

- (void)justPush:(NSNotification *) notification {
    //处理消息
    
    UIViewController *c = [[UIViewController alloc]init];
    c.view.backgroundColor = [UIColor purpleColor];
    [self.navigationController pushViewController:c animated:YES];
    
}
- (void)dealloc {
    //单条移除观察者
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:[NSString stringWithFormat:@"%@2",kNotificationMessagePush] object:nil];
    //移除所有观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
第三步,注意⚠️!
  • 也许你看到了我在发送、注册通知的时候,有一行注释,区别在于name的变化,这里为什么要利用一个tabTag来做name的区分呢?
  • 原因:通知是一对多的模式,如果我name不做区分,会产生一个bug,那就是,假如我在第一个item,点击第二个item,这时会直接push,没错,再点一个第二个item,直接push,再返回也没错,但是如果再点击第三个item,问题来了,它也会直接push,原因是它已经在之前就接到了通知。
  • bug的gif图如下:


    bug效果图.gif
  • 结语:有段时间没持续更技术了,踏上新的旅程,记录新的问题,期待成长

相关文章

网友评论

    本文标题:iOS 点击tabbar的一个item,直接push新页面,而不

    本文链接:https://www.haomeiwen.com/subject/bvklwqtx.html