How to add a image at the center of navigationBar in Objective-C? How to add a image at the center of navigationBar in Objective-C? ios ios

How to add a image at the center of navigationBar in Objective-C?


Set navigation title view like below

self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img.png"]];



EDIT:
if you have big image then use below code

UIImage *img = [UIImage imageNamed:@"1.png"];UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];[imgView setImage:img];// setContent mode aspect fit[imgView setContentMode:UIViewContentModeScaleAspectFit];self.navigationItem.titleView = imgView;


As you said to set an icon for the application. You may like to go for this which will show icon for whole application.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon"]];CGSize imageSize = CGSizeMake(40, 40);CGFloat marginX = (self.navigationController.navigationBar.frame.size.width / 2) - (imageSize.width / 2);imageView.frame = CGRectMake(marginX, 0, imageSize.width, imageSize.height);[self.navigationController.navigationBar addSubview:imageView];

OutPut:

enter image description here


I was facing the same issue, since iOS 11 and Xcode 9 started managing the Navigation Bars with auto layout instead of frames you should be aware of your Navigation Bar layout.

In the WWDC Session 204, Updating your app for iOS 11, was stated that UIToolBar and UINavigationBar was upgraded to use auto layout, and in order to avoid Zero-Sized Custom Views you should know a few things about it.

UINavigation and UIToolBar provide position, do not care about it.

You must provide the size of the Custom view with one of the following:

  • Constraints for width and height.
  • Implement intrinsicContentSize
  • Connect your subviews via constraints.

Answering your question, I set the titleView with a ImageView,providing the size in two different ways:

Giving Height and width explicitly.

-(void)updateNavTitleView{    UIImageView *imageView = [[UIImageView alloc] initWithImage:[ UIImage imageNamed:@"TitleViewImage"]];    [imageView.widthAnchor constraintEqualToConstant:160].active = YES;    [imageView.heightAnchor constraintEqualToConstant:44].active = YES;    self.navigationItem.titleView = imageView;}

Or setting the aspect mode as aspectFit

-(void) updateNavTitleView{    UIImageView *imageView = [[UIImageView alloc] initWithImage:[ UIImage imageNamed:@"TitleViewImage"]];    [imageView setContentMode:UIViewContentModeScaleAspectFit];    self.navigationItem.titleView = imageView;}

In case you want to watch the Session, Session 204