1

Я пытался решить эту проблему, но я не могу понять, как это сделать.Reload navigationBar UIBarButtonItems

У меня есть UIButton, которому необходимо добавить в качестве подзаголовка.

Мне нужно обновить это UIButton, потому что у меня нет необходимого числа, пока метод не вызван через NSNotification.

Дело в том, что с этим кодом UIBarButtonItem занимает слишком много времени, и если прокручивается UITableView (navBar исчезает), обе кнопки исчезают (даже при появлении навигационной панели).

- (void) addSettingsButton { 
    self.navigationItem.rightBarButtonItems = nil; 

    UIButton * button2 = [UIButton buttonWithType:UIButtonTypeSystem]; 
    button2.frame = CGRectMake(0, 0, 19, 19); 
    [button2 setImage:[UIImage imageNamed:@"settingsBtn.png"] forState:UIControlStateNormal]; 
    button2.tintColor = [UIColor grayColor]; 
    [button2 addTarget:self action:@selector(showSettings) forControlEvents:UIControlEventTouchUpInside]; 
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button2]; 
    UIBarButtonItem* button2Aux = [[UIBarButtonItem alloc] initWithCustomView:button2]; 

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 19, 19)]; 

    UIButton * button3 = [UIButton buttonWithType:UIButtonTypeSystem]; 
    button3.frame = CGRectMake(0, 4, 23, 15.5); 

    int altoPantalla = [UIScreen mainScreen].bounds.size.height; 

    [button3 setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"Icon_Buzon.png"]] forState:UIControlStateNormal]; 

    [button3 addTarget:self action:@selector(showTut) forControlEvents:UIControlEventTouchUpInside]; 

    [view addSubview:button3]; 

    NSString *cantNotificaciones = self.cantNotificaciones; 
    NSInteger posX = 0, posY = 0, ancho = 0, alto = 0, radio; 
    BOOL ponerCirculo = NO; 

    if (cantNotificaciones.length >= 3) { 

     cantNotificaciones = @"+99"; 
     posX = 10.5; 
     posY = 12; 
     ancho = 21; 
     alto = 15; 
     radio = 8; 
     ponerCirculo = YES; 

    } else if (cantNotificaciones.length == 2 || (cantNotificaciones.length == 1 && ![cantNotificaciones isEqualToString:@"0"])) { 

     posX = 8; 
     posY = 12; 
     ancho = 16; 
     alto = 16; 
     radio = 8; 

     ponerCirculo = YES; 
    } else { 
     ponerCirculo = NO; 
    } 

    if (ponerCirculo) { 

     UILabel *lbl3 = [[UILabel alloc] initWithFrame:CGRectMake(button3.center.x-posX, -posY, ancho, alto)]; 
     [lbl3 setText:cantNotificaciones]; 
     lbl3.textColor = [UIColor whiteColor]; 
     lbl3.backgroundColor = [UIColor redColor]; 
     [lbl3 setFont:[UIFont systemFontOfSize:10]]; 
     lbl3.layer.cornerRadius = radio; 
     lbl3.clipsToBounds = YES; 
     [lbl3 setTextAlignment:NSTextAlignmentCenter]; 
     [button3 addSubview:lbl3]; 

    } else { 

    } 

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showTut)]; 
    [tap setNumberOfTouchesRequired:1]; 
    [tap setNumberOfTapsRequired:1]; 
    [view addGestureRecognizer:tap]; 

    UIBarButtonItem* button3Aux = [[UIBarButtonItem alloc] initWithCustomView:view]; 

    switch (altoPantalla) { 
     case 480: 
      posicionX = -7; 
      space = 21; 
      break; 
     case 568: 
      posicionX = -10; 
      space = 21; 
      break; 
     case 667: 
      posicionX = 19; 
      space = 27; 
      break; 
     case 736: 
      posicionX = 19; 
      space = 40; 
      break; 
     default: 
      break; 
    } 

    UIBarButtonItem *positiveSpacer = [[UIBarButtonItem alloc] 
            initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace 
            target:nil action:nil]; 
    positiveSpacer.width = space; 

    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:button2Aux, positiveSpacer, button3Aux, nil]; 
    [self.view setNeedsLayout]; 
    [self.view setNeedsDisplay]; 
} 

-(void) modificarNumeroBoton:(NSNotification *) notification 
{ 
    NSString *cantidad = (NSString *)[notification object]; 
    NSLog(@"Numero recibido: %@",cantidad); 

    self.cantNotificaciones = cantidad; 
    [self addSettingsButton]; 
} 

Для меня есть два возможных решения: либо сделать обновление немедленного (было бы лучше), или сделать так, кнопки не исчезают при прокрутке

ответ

0

Если вы хотите, чтобы перезагрузить текст метки или затем просмотрите таблицу в потоке Main.

Уведомления о работе над нитями, отличными от основного, если не указано иное.

ли это:

dispatch_async(dispatch_get_main_queue(), ^(void){ 
     //Update the label text 
     // Update the Tableview 
}); 
+0

Спасибо, я новичок в Objective-C, где я должен поместить это? –

+0

Я уже понял, где, спасибо! –

+0

Отлично! Добро пожаловать :) –