问题
I want to put an icon by side of the title of my navigation bar. I'd prefer not to implement it as a custom titleView, because then i'll need to create a custom titleView for each controller i put on the stack (and I have pretty deep nesting). I'm adding currently as an UIImageView to a navigationBar. My problem is to calculate exactly this icon's horizontal position. It depends on the width of the back button, which has each time another title. How do I calculate this back button frame? Googling on it seems doesn't bring any reasonable results.
Thanks in advance
回答1:
You could calculate the size of a label, with your text in it and experiment with what the button will add on..
CGSize s = [label sizeWithFont:_font];
回答2:
I ran into this same issue. My solution was to add the icon as one of the leftBarButtonItems, after a flexible space. This pushes it up against the title.
UIBarButtonItem *space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
UIView *icon = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"titleIcon"]] autorelease];
UIBarButtonItem *iconItem = [[[UIBarButtonItem alloc] initWithCustomView:icon] autorelease];
NSArray *items = [NSArray arrayWithObjects: space, iconItem, nil];
self.navigationItem.leftBarButtonItems = items;
self.navigationItem.leftItemsSupplementBackButton = YES;
It's not quite the same as creating a custom titleView, however, in two ways: (1) the title text remains centered if possible, with the icon to its left, rather than centering the title and icon together; and (2) when you push a new view onto the stack, the icon does not slide to the left with the title; instead it fades out, like the other bar button items.
So, depending on your requirements, this solution may or may not work for you. But at least it avoids trying to match the standard title text attributes in a custom title view. (As far as I can discover, there is no automatic way to do that.)
来源:https://stackoverflow.com/questions/4323934/adding-icon-between-back-button-title-of-navigation-bar