2

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

4

1 回答 1

12

这是我所做的

 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;

您可能会注意到我在设置 navigationItem 的 titleView 之前将 UIImageView 实例添加到 UIView 实例。您可以直接将 UIImageView 实例设置为 navigationItem 的 titleView,但是当您导航到下一页时徽标会偏离中心,并且您仍然希望使用后退按钮显示徽标。导航栏会自动把UIView放在中间,但是UIImageView(虽然UIImageView是UIView的子类,只是不知道为什么)。

于 2014-02-21T19:43:02.257 回答