Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add UIActivityIndicatorView into UIBarButtonItem on UINavigationBar (iOS)

I have found a great article how to add an Activity Indicator inside Bar Button on Navigation Bar. But I cannot repeat this in my case. I have added both Navigation Bar and UIBarButton in code (not in nib) but I could not find an element named UINavigationButton to put Activity Indicator inside.

I want that UIBarButtonItem button is visible:

enter image description here

And not like that:

enter image description here

Does anyone have a suggestion how to make this work?

like image 725
Borut Tomazin Avatar asked May 06 '12 09:05

Borut Tomazin


1 Answers

A rough work-around could be something like this:

 act=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
 [act setFrame:CGRectMake(14, 5, 20, 20)];
 [act startAnimating];
 rightButt=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:nil];
 self.navigationItem.rightBarButtonItem=rightButt;
 if ([[self.navigationController.navigationBar subviews] count]>=2) {
     //Be careful with the next line, Here you get access to an static index, 
     //Apple could change the structure of the navbar and your index may change in the future.
     [[[self.navigationController.navigationBar subviews] objectAtIndex:2] addSubview:act];    

    }

And you'll get this:

enter image description here

EDIT:
From your comment it seems that you want to add this button inside UIToolbar, not in a UINavigationBar, it's pretty the same:

UIActivityIndicatorView* act=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[act setFrame:CGRectMake(10, 13, 20, 20)];
[act startAnimating];
UIBarButtonItem *rightButt=[[UIBarButtonItem alloc] initWithTitle:@"      " style:UIBarButtonItemStyleBordered target:self action:nil];
UIToolbar *tb=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[tb setBarStyle:UIBarStyleBlack];
[tb setItems:[NSArray arrayWithObjects:rightButt, nil]];
if ([[tb subviews] count]>=1) {
    [[[tb subviews] objectAtIndex:1] addSubview:act];      
}

and you'll get this:

enter image description here

like image 183
Mat Avatar answered Sep 26 '22 01:09

Mat