NavigationItem Titleview centered on the navigationbar under IOS 7 - impossible?

6.2k views Asked by At

I'm asking since the usual answer, modifying the frame in viewDidLayoutSubviews, does not work - unless you can find a mistake in my code. The frame gets set to the correct width and height, but iOS 7 does not respect the frame.

Currently, the app released long ago looks like this and works on iOS 6 and 7: https://itunes.apple.com/se/app/eksjo/id435475192?mt=8

Recompiling gives this: https://www.dropbox.com/s/pzyv2vhtlmlxkoe/Photo%202013-12-11%2009%2047%2030.png

-(void)viewWillAppear:(BOOL)animated {
    UIImageView *iv=[[UIImageView alloc] initWithFrame:r(320-102/2,0,102,44)];
    iv.image=[UIImage imageNamed:@"Eksjologo5bar.png"];
    self.navigationItem.titleView=iv;
    [iv release];
}

-(void)viewDidLayoutSubviews {
    CGRect frame=self.navigationItem.titleView.frame;
    frame.size.width=102;
    frame.size.height=44;
    self.navigationItem.titleView.frame=frame;
}

All I want to do is put a logo image in the center of the Navigation Bar. I'm looking for a minimum code change to the viewWillAppear code to do this and still be compatible with iOS 6.x.

Edit: It may also be an iOS 6 issue and not an iOS 7 issue. If you can explain why it should be done like in this question, it's an answer to my question: My UINavigationitem's TitleView getting expanded in ios 6

1

There are 1 answers

0
Dino Tw On

Here is what I do

 UIImageView *logoImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, desired_image_width, desired_image_height)];
 // if you need to resize the image to fit the UIImageView frame
 logoImage.contentMode = UIViewContentModeScaleAspectFit;
 // no extension name needed for image_name
 [logoImage setImage:[UIImage imageNamed:@"image_name"]];
 UIView *logoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, logoImage.frame.size.width, logoImage.frame.size.height)];
 [logoView addSubview:logoImage];
 self.navigationItem.titleView = logoView;

You may notice that I add the UIImageView instance to an UIView instance before setting the navigationItem's titleView. You may set the UIImageView instance to navigationItem's titleView directly, but the logo will be off center when you navigate to the next page and you still want to show the logo with the back button. The navigation bar will automatically put the UIView in the center, but UIImageView (although UIImageView is a subclass of UIView, I just don't know why).