¿Cómo establecer el valor de la insignia en la barra de pestañas?


Tengo que leer datos de xml y tengo que mostrar valores en view controller. estoy usando tab barcontroller . donde tengo que leer datos xml y tengo que mostrarlos en la barra de pestañas como insignia. aquí está el código de mi controlador.

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{

    if([elementName isEqualToString:@"Event"]) {
        //Initialize the array.
        rssOutputData  = [[NSMutableArray alloc] init];
        mycount = [attributeDict objectForKey:@"count"];
         NSLog(@"Reading count value :%@",mycount);
    }
    else if([elementName isEqualToString:@"eventdashboard"]) {
        //Initialize the book.
        aEvent = [[Eventlist alloc] init];
        //Extract the attribute here.
        aEvent.id = [[attributeDict objectForKey:@"userid"] integerValue];
        NSLog(@"Reading id value :%d", aEvent.id);
    }
    NSLog(@"Processing Element: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if(!nodecontent)
        nodecontent = [[NSMutableString alloc] initWithString:string];else
            [nodecontent appendString:string];
    NSLog(@"Processing Value: %@", nodecontent);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if([elementName isEqualToString:@"Event"])
        return;
    if([elementName isEqualToString:@"eventdashboard"]) {
        [rssOutputData addObject:aEvent];
        [aEvent release];
        aEvent= nil;
        }
    else
        [aEvent setValue:nodecontent forKey:elementName];
    [nodecontent release];
    nodecontent = nil;

}
- (void)viewDidLoad
{

        [super viewDidLoad];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg2.jpeg"]];
        NSLog(@"%d",memberid);
        myid = [SingleTonClass sinlgeTon].memberIdOne;
        NSString *post =[[NSString alloc] initWithFormat:@"userid=%d",myid];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        NSURL *url = [NSURL URLWithString:@"http://journalonline.in/cfts/dashboards/dashboard?"];
        NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
        // [theRequest addRequestHeader:@"Content-Type" value:@"application/xml"];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setValue:@"application/xml" forHTTPHeaderField:@"Accept"];
        [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [theRequest setHTTPBody:postData];
        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        if( theConnection )
        {
            webData = [[NSMutableData data] retain];
            NSLog(@"%@",webData);
        }
        }

-(void)viewWillAppear:(BOOL)animated{
    [tblView reloadData];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
    [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    eventarray = [[NSMutableArray alloc]init];
    xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
    [xmlParserObject setDelegate:self];
    [xmlParserObject parse];


     for (int i =0; i<[rssOutputData count]; i++) {
        Eventlist *log = [rssOutputData objectAtIndex:i];
        eventid = log.id;
        NSLog(@"%d",eventid);
        Invit = log.invitationdet; 
        NSLog(@"%@",Invit);

        [eventarray addObject:log];
    }


    [connection release];
    [tblView reloadData];
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSString * segueIdentifier = [segue identifier];
    if([segueIdentifier isEqualToString:@"MainEventList"]){
        UINavigationController *nav = [segue destinationViewController];
        MaineventListController *MVC = (MaineventListController *)nav.topViewController;
        MVC.memberid1 = [SingleTonClass sinlgeTon].memberIdOne;
        NSLog(@"%d",MVC.memberid1);
    }
    if ([segue.identifier isEqualToString:@"EventListDetail"])
    {
        NSIndexPath *indexPath = [tblView indexPathForSelectedRow];
        [[SingleTonClass sinlgeTon] addObjectsColorArray:[NSString stringWithFormat:@"%d",indexPath.row]];
        MainEventDetailController *destViewController = segue.destinationViewController;
        MainEvent *aEvent1 = [eventarray objectAtIndex:indexPath.row];
        destViewController.eveID = aEvent1.id;
        destViewController.usrid =  [SingleTonClass sinlgeTon].memberIdOne;
    }
}

-(void)didReceiveMemoryWarning  {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [eventarray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0)
        return  [eventarray count];
    if (section == 1)
        return 1;
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"eventCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(indexPath.section == 0)
    {
        Eventlist *msglist = [eventarray objectAtIndex:indexPath.row];
        cell.textLabel.text = msglist.invitationdet;
        NSLog(@"Array %@",[SingleTonClass sinlgeTon].colorArray);
        NSInteger stat=msglist.readflag;
        if([[SingleTonClass sinlgeTon].colorArray containsObject:[NSString stringWithFormat:@"%d",indexPath.row]] || stat == 1 ) {
            NSInteger stat1 = msglist.responseflag;
            if(stat1 == 1){
                cell.textLabel.textColor = [UIColor yellowColor];
            }
            else {
             cell.textLabel.textColor = [UIColor redColor];
            }
        }
               else{
        cell.textLabel.textColor = [UIColor greenColor];
        }
        cell.backgroundColor = [UIColor blackColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
          }
    if(indexPath.section == 1)
    {
        UIButton *viewmoreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        viewmoreButton.frame = CGRectMake(200.0f, 5.0f, 80.0f, 30.0f);
        [viewmoreButton setTitle:@"View More" forState:UIControlStateNormal]; 
        [cell addSubview:viewmoreButton];
        [viewmoreButton addTarget:self
                           action:@selector(viewMore:)
                 forControlEvents:UIControlEventTouchUpInside];
        cell.backgroundColor = [ UIColor blackColor];
    }
    return cell;
}
- (void)viewMore:(id)sender
{
    [self performSegueWithIdentifier:@"MainEventList" sender:sender];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void) dealloc
{
    [xmlParserObject release];
    [super dealloc];
}

Aquí estoy leyendo un valor de XML

 mycount = [attributeDict objectForKey:@"count"];

No sé mostrar en la barra de pestañas como insignia. traté de mostrarlo bajo viewDidLoad pero no funcionó pls me ayudan amigos

Author: user2728139, 2013-11-18

8 answers

Déjame decirte la forma más sencilla de establecer el valor de la insignia:

[[self navigationController] tabBarItem].badgeValue = @"YourBadgeValue";
 67
Author: Vineet Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-18 09:38:03

La respuesta de Vineet Singh es buena si quieres cambiar la insignia de la pestaña actual. Si en su lugar necesita cambiar el valor de otra pestaña que tiene en su barra de pestañas, use lo siguiente:

Objective-C

[[self.tabBarController.tabBar.items objectAtIndex:0] setBadgeValue:nil];

Swift

tabBarController?.tabBar.items?[0].badgeValue = nil

Recuerde reemplazar el índice que utilicé con la pestaña real para la que desea editar el valor.

 49
Author: Andrea Gottardo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-05 20:41:57
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
UITabBarItem *tbItem = (UITabBarItem *)[appDelegate.tabBarController.tabBar.items objectAtIndex:tabIndex];
tbItem.badgeValue = [NSString stringWithFormat:@"%i", count];
 5
Author: Sandeep-Systematix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-18 09:38:49

Veo algunas respuestas acerca de establecer esto en el TabItem, pero si la pestaña nunca se ha cargado, la función viewDidLoad nunca se cargará. Esto es especialmente importante cuando intenta crear un proceso en segundo plano, como el manejo de notificaciones push, establecer una insignia de pestaña. Es mucho más probable que necesite su TabViewController para manejar la configuración de la insignia. Las etiquetas en el TabItem parecen más apropiadas y luego voltear a través de las pestañas hasta que encuentre la que desea actualizar.

¡Salud!
 1
Author: BK-,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-11 18:23:46

Prueba esto:

tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",count];
 1
Author: Bhumeshwer katre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-02 11:05:19

Swift 2.0:

    self.navigationController!.tabBarItem.badgeValue = "YourBadgeValue"
 1
Author: Bill Chan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-11 23:18:10
int indexOfTabbarItem = 0;
    NSString *badgeValue = [NSString stringWithFormat:@"%lu", (long)countUnreadMessages];

    [[[[self viewControllers] objectAtIndex:indexOfTabbarItem] tabBarItem] setBadgeValue:([badgeValue isEqualToString:@"0"]) ? nil : badgeValue];

Esto funcionó para mí. Algunas veces tienes que encontrar el controlador correcto y luego su elemento para configurarlo. Aclamaciones.

 0
Author: Waleed Mahmood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-24 16:08:24

Para ionic angular, simplemente enlaza el valor a tabBadge

  <ion-tab [root]="tab3Root" tabIcon="notifications" tabBadgeStyle="red" tabBadge={{totalUnread}}></ion-tab>
 -1
Author: Aymen Boumyza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-08 21:38:45