So i am trying to add an UIImageview in titleview property of the UINavigationbar using the following code. The issue is that although i put specific size to the UIView that contains the UIImageview which contains the image it does not work as expected. The result is a bigger image in the Navigation bar than the one i set with the CGRectMake. Also in some views it does not align to the center! What am i missing? Is there another way to add the image to the navbar?
-(void)viewDidLayoutSubviews{
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,10.0f,16.0f)];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,10.0f,16.0f)];
CGSize imageSize = CGSizeMake(10, 16);
CGFloat marginX = (self.navigationController.navigationBar.frame.size.width / 2) - (imageSize.width / 2);
imageView.frame = CGRectMake(marginX, 11, imageSize.width, imageSize.height);
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIImage *image = [UIImage sdk_imageName:@"logo.png"];
[imageView setImage:image];
[containerView addSubview:imageView];
self.navigationItem.titleView=imageView;
}
CodePudding user response:
I reviewed your code and i found some frame issues and at the bottom you are not passing container view in titleview, that will not render the view as expected.
Please try this one.
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,self.navigationController.navigationBar.frame.size.width,self.navigationController.navigationBar.frame.size.height)];
UIImageView *imageView = [[UIImageView alloc] init];
//containerView.backgroundColor = [UIColor redColor];
CGSize imageSize = CGSizeMake(60, self.navigationController.navigationBar.frame.size.height);
CGFloat marginX = (self.navigationController.navigationBar.frame.size.width / 2) - (imageSize.width / 2);
imageView.frame = CGRectMake(marginX, 0, imageSize.width, imageSize.height);
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIImage *image = [UIImage imageNamed: @"2.jpg"];
[imageView setImage:image];
[containerView addSubview:imageView];
self.navigationItem.titleView=containerView;
CodePudding user response:
Much simpler approach... use auto-layout constraints for the image view size... centering is handled automatically.
10x16
image view as the titleView
:
UIImage *img = [UIImage imageNamed:@"logo"];
UIImageView *titleImageView = [[UIImageView alloc] initWithImage:img];
titleImageView.contentMode = UIViewContentModeScaleAspectFit;
titleImageView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[titleImageView.widthAnchor constraintEqualToConstant:10.0],
[titleImageView.heightAnchor constraintEqualToConstant:16.0],
]];
self.navigationItem.titleView = titleImageView;