Question

I have a navbar with the following:

left: back arrow with the word "back" all the way to the left

right: 2 bar buttons all the way to the right

center: title text

I want to add a third button to the pair buttons on the right (to the left of those buttons), but I want there to be space between this new button and the other buttons such that this new button is hugging up on the right side of the title. I tried using a FixedSpace BarButtonItem. Here's what I've got so far:

UIBarButtonItem* space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
space.width = 160;
UIBarButtonItem* thirdButton = [[UIBarButtonItem alloc] initWithImage:myImage style:UIBarButtonItemStylePlain target:self action:@selector(action)];

NSMutableArray* buttons = [self.navigationItem.rightBarButtonItems mutableCopy];       
//index 0 & 1 are the buttons that are already there
[buttons setObject:space atIndexedSubscript:2];
[buttons setObject:button atIndexedSubscript:3];
[self.navigationItem setRightBarButtonItems:buttons];

Doing this does indeed create a space between the third button and the other buttons. Problem is though, the title can be dynamic, and it's not alway center because of this fixed space. Adding a fixed space to the right causes the title to shift to the left and look weird depending on the title size. I need a way to figure out the position of the title and how long it is. Is there a way to do that? Something like navBar.title.width and navBar.title.origin so that I can figure out how many points there are from the very right of the navbar until the title?

Was it helpful?

Solution

To calculate the size of the title in the nav bar, you'll just need to following.

NSDictionary *attributes = [self.navigationController.navigationBar titleTextAttributes];
CGSize titleSize = [self.title sizeWithAttributes:attributes];

Now you can use the size of the title and the size of the buttons to calculate the width of the fixed space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top