ezescaruli / ESTabBarController

A custom tab bar controller for iOS.
MIT License
127 stars 23 forks source link

How to change tabBarItem.badgeValue ? #10

Closed LunevNF closed 8 years ago

LunevNF commented 8 years ago

How can I change a badge value of tabItem? I was try: tabBarController_.tabBarController.selectedViewController.tabBarItem.badgeValue = @"23"; But value not changed. Help, please. :)

LunevNF commented 8 years ago

Ohh, ESTabBarController returns nil of tabBarController. That's why I was change Pod project of ESTabBarController and add some code. I think, that a lot of people can't find a normal way for this issue. This code from my project may help you:

Because of we get PUSH-info in appDelegate.h, we must create some variables here. This varibles are contains count numbers for 4 tabs. Paste from my AppDelegate.m:

`//
//  AppDelegate.m
//
#import "ESTabBarController.h"

@interface AppDelegate ()
@end

NSString *tabBadge0, *tabBadge1, *tabBadge2, *tabBadge3, *tabBadge4;
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//some code...

//Получение версии ОС
NSString *ver = [[UIDevice currentDevice] systemVersion];
//int ver_int = [ver intValue];
float ver_float = [ver floatValue];

//Register PUSH-permissions
if (ver_float < 8.0){
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}

if (ver_float >= 8.0){
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

//Try get PUSH-info (when app opened after app's full shutdown)
NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

if (userInfo) {
    //example of getting numbers from PUSH for tabs
    NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];

    NSArray *notice = [userInfo objectForKey:@"notices"];
    NSDictionary *questAnswer_ = [notice objectAtIndex:0];
    NSDictionary *news_ = [notice objectAtIndex:1];
    NSDictionary *npa_ = [notice objectAtIndex:2];
    NSDictionary *msgsAnswer = [notice objectAtIndex:3];                

    //And now we save those numbers to our String variables was implemented before
    tabBadge1 = [NSString stringWithFormat:@"%d",[[questAnswer_ objectForKey:@"count"] integerValue]];
    tabBadge2 = [NSString stringWithFormat:@"%d",[[news_ objectForKey:@"count"] integerValue]];
    tabBadge3 = [NSString stringWithFormat:@"%d",[[npa_ objectForKey:@"count"] integerValue]];
    tabBadge4 = [NSString stringWithFormat:@"%d",[[msgsAnswer objectForKey:@"count"] integerValue]];

    //copy values from appDelegate to ESTabBarController
    tabBarController_.tabBadge1 = tabBadge1;
    tabBarController_.tabBadge2 = tabBadge2;
    tabBarController_.tabBadge3 = tabBadge3;
    tabBarController_.tabBadge4 = tabBadge4;

    //Change main Badge for App Icon in main IPhone menu
    NSInteger badgeSum = [[questAnswer_ objectForKey:@"count"] integerValue]
    + [[news_ objectForKey:@"count"] integerValue]
    + [[npa_ objectForKey:@"count"] integerValue]
    + [[msgsAnswer objectForKey:@"count"] integerValue];
    [UIApplication sharedApplication].applicationIconBadgeNumber = badgeSum;
}

//Register you device Token for PUSH
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken  {
NSMutableString *tokenString = [NSMutableString stringWithString:
                                [[deviceToken description] uppercaseString]];
[tokenString replaceOccurrencesOfString:@"<"
                             withString:@""
                                options:0
                                  range:NSMakeRange(0, tokenString.length)];
[tokenString replaceOccurrencesOfString:@">"
                             withString:@""
                                options:0
                                  range:NSMakeRange(0, tokenString.length)];
[tokenString replaceOccurrencesOfString:@" "
                             withString:@""
                                options:0
                                  range:NSMakeRange(0, tokenString.length)];
NSLog(@"My token is: %@", tokenString);
self.device_token = tokenString;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Ошибка получения токена: %@", error);
}

//Work with input PUSH (as at didFinishLaunchingWithOptions)
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@"Received notification: %@", userInfo);
NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];

NSArray *notice = [userInfo objectForKey:@"notices"];
NSDictionary *questAnswer_ = [notice objectAtIndex:0];
NSDictionary *news_ = [notice objectAtIndex:1];
NSDictionary *npa_ = [notice objectAtIndex:2];
NSDictionary *msgsAnswer = [notice objectAtIndex:3];

tabBadge1 = [NSString stringWithFormat:@"%d",[[questAnswer_ objectForKey:@"count"] integerValue]];
tabBadge2 = [NSString stringWithFormat:@"%d",[[news_ objectForKey:@"count"] integerValue]];
tabBadge3 = [NSString stringWithFormat:@"%d",[[npa_ objectForKey:@"count"] integerValue]];
tabBadge4 = [NSString stringWithFormat:@"%d",[[msgsAnswer objectForKey:@"count"] integerValue]];

tabBarController_.tabBadge1 = tabBadge1;
tabBarController_.tabBadge2 = tabBadge2;
tabBarController_.tabBadge3 = tabBadge3;
tabBarController_.tabBadge4 = tabBadge4;

NSInteger badgeSum = [[questAnswer_ objectForKey:@"count"] integerValue]
+ [[news_ objectForKey:@"count"] integerValue]
+ [[npa_ objectForKey:@"count"] integerValue]
+ [[msgsAnswer objectForKey:@"count"] integerValue];
[UIApplication sharedApplication].applicationIconBadgeNumber = badgeSum;        
}

//
//  AppDelegate.h
//

#import "ESTabBarController.h"
@property (nonatomic, strong) ESTabBarController *tabBarController_;

//
//  YourWorkSpace/Pods/ESTabBarController/ESTabBarController.h
//

@property (nonatomic, strong) NSString *tabBadge0, *tabBadge1, *tabBadge2, *tabBadge3, *tabBadge4;

//
//  YourWorkSpace/Pods/ESTabBarController/ESTabBarController.m
//

#import "JSBadgeView.h" //install this POD to your project and import here
#import <QuartzCore/QuartzCore.h> //Must import too 

//Change this metod something like this
- (void)moveToControllerAtIndex:(NSInteger)index animated:(BOOL)animated {
if (self.selectedIndex == index) {
    // Nothing to do.
    return;
}

UIViewController *controller = self.controllers[@(index)];

if (controller != nil) {

    // Deselect all the buttons excepting the selected one.
    for (NSInteger i = 0; i < self.buttons.count; i++) {
        UIButton *button = self.buttons[i];

        //Input badge numbers with JSBadgeView
        switch (i) {
            case 1:{
                JSBadgeView *badgeView =
                [[JSBadgeView alloc] initWithParentView:button alignment:JSBadgeViewAlignmentCenterLeft];
                badgeView.badgeText = tabBadge1;
            }
                break;
            case 2:{
                JSBadgeView *badgeView =
                [[JSBadgeView alloc] initWithParentView:button alignment:JSBadgeViewAlignmentCenterLeft];
                badgeView.badgeText = tabBadge2;
            }
                break;
            case 3:{
                JSBadgeView *badgeView =
                [[JSBadgeView alloc] initWithParentView:button alignment:JSBadgeViewAlignmentCenterLeft];
                badgeView.badgeText = tabBadge3;
            }
                break;
            case 4:{
                JSBadgeView *badgeView =
                [[JSBadgeView alloc] initWithParentView:button alignment:JSBadgeViewAlignmentCenterLeft];
                badgeView.badgeText = tabBadge4;
            }
                break;
            default:
                break;
        }

        BOOL selected = (i == index);
        button.selected = selected;

        if (self.highlightsSelectedButton && !(self.actions[@(i)] != nil && self.controllers[@(i)] == nil)) {
            // Only if the selected button highlighting is enabled and
            // the button either has a controller, or a controller and an
            // action.
            button.alpha = selected ? 1.0 : 0.5;
        }
    }

    if (self.selectedIndex >= 0) {
        // Remove the current controller's view.
        UIViewController *currentController = self.controllers[@(self.selectedIndex)];
        [currentController.view removeFromSuperview];
    }

    if (![self.childViewControllers containsObject:controller]) {
        // If I haven't added the controller to the childs yet...
        [self addChildViewController:controller];
        [controller didMoveToParentViewController:self];
    }

    if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) {
        // Table views have an issue when disabling autoresizing
        // constraints in iOS 7.
        // Their width is set to zero initially and then it's not able to
        // adjust it again, causing constraint conflicts with the cells
        // inside the table.
        // For this reason, we just adjust the frame to the container
        // bounds leaving the autoresizing constraints enabled.
        [self.controllersContainer addSubview:controller.view];
        controller.view.frame = self.controllersContainer.bounds;
    } else {
        controller.view.translatesAutoresizingMaskIntoConstraints = NO;
        [self.controllersContainer addSubview:controller.view];
        [self setupConstraintsForChildController:controller];
    }

    [self moveSelectionIndicatorToIndex:index animated:animated];

    _selectedIndex = index;
}
}`

For creating of badges on UIView I used this POD: https://github.com/JaviSoto/JSBadgeView because this tabBarController not set badge even this metod: AppDelegate *appD = [AppDelegate sharedAppDelegate]; appD.tabBarController_.tabBarController.selectedViewController.tabBarItem.badgeValue = @"23"; That's all. Hope this help you and sorry for my Russian English. :) Remember: you must init tabBarController_ and send class-value to AppDelegate. Writen by Lunev Nikita. You can send your questions here: lunev-nikita@yandex.ru

ezescaruli commented 8 years ago

Hi, @lukitnev! Yeah, ESTabBarController still doesn't support badges in its latest version, nor in its master branch.

However, there's a fork waiting to be merged in https://github.com/ezescaruli/ESTabBarController/pull/7, that has support for badges. It still has some fixes to do in the code before merging it, but you can use the fork if it fits your needs.

Eze

ezescaruli commented 8 years ago

I'll close this issue as it's covered in #7.

LunevNF commented 8 years ago

Thanks for answer. Yes, can close. :)