Search code examples
iosobjective-cuinavigationitem

UINavigationItem setLeftBarButtonItems Delay


I have a rather confusing problem: In my application I am checking for network connectivity and if the user is not connected to the internet I am showing a little red exclamation mark in the navigation bar.

The Code that is used to show the exclamation mark looks like this:

    - (void)showConnectivityMessage
{
    UIBarButtonItem *exclamationMark = [[UIBarButtonItem alloc]initWithTitle:@"!" style:UIBarButtonItemStyleDone target:self action:@selector(showConnectivityInfo)];
    [exclamationMark setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],
                                              NSFontAttributeName:[UIFont boldSystemFontOfSize:22]} forState:UIControlStateNormal];

    NSMutableArray *items = [NSMutableArray arrayWithArray:self.navigationItem.leftBarButtonItems];
    [items addObject:exclamationMark];
    [self.navigationItem setLeftBarButtonItems:items];
    NSLog(@"Should show exclamation mark!");

}

The method is called correctly and I can see the output "Should show exclamation mark!". Now, whats weird is that it takes another ~20s until the new navigation item actually appears...

Does anyone have an idea on where this delay could be coming from? Any help resolving the error would be greatly appreciated!


Solution

  • Every time you see a similar delay in UI, it is because you haven't updated the UI from the main thread. Always update UI only from the main thread.

    dispatch_async(dispatch_get_main_queue(), ^{
        UIBarButtonItem *exclamationMark = [[UIBarButtonItem alloc]initWithTitle:@"!" style:UIBarButtonItemStyleDone target:self action:@selector(showConnectivityInfo)];
       [exclamationMark setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],
                                              NSFontAttributeName:[UIFont boldSystemFontOfSize:22]} forState:UIControlStateNormal];
    
        NSMutableArray *items = [NSMutableArray arrayWithArray:self.navigationItem.leftBarButtonItems];
        [items addObject:exclamationMark];
        [self.navigationItem setLeftBarButtonItems:items];
        NSLog(@"Should show exclamation mark!");
    }