Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling size / position of UINavigationItem titleView

In my app, I have some custom titles (with lettering that isn't a font) stored in pngs that I want to put as the title of my navigation. I want the lettering in the titles all to be the same size for each different view controller, so in illustrator I've worked on making it all the same size and width (affording blank space to account for shorter strings). I do the following:

UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SelectAnAlbumTitleLettering"]];
titleImageView.contentMode = UIViewContentModeCenter;
self.navigationItem.titleView = titleImageView;
[titleImageView release];

And it seems the image is arbitrarily resized and positioned based on the elements included on each navigationBar (i.e. back button, right button etc.).

I'm wondering, how can I gain control of titleView so I can make it implement the size and position that I want and so it isn't arbitrarily resized / repositioned.

like image 556
Ser Pounce Avatar asked Apr 17 '13 20:04

Ser Pounce


3 Answers

Instead of using your image view as the title view, create another view that contains the image view. Set that view as the title view of the navigation item; now you’re free to adjust the image view’s frame within the title view.

like image 144
Jeff Kelley Avatar answered Sep 30 '22 10:09

Jeff Kelley


You can control size and position of UINavigationbar titleview. Don't set imageview as titleview directly. Instead create a custom UIView and then set its frame as per your requirement and add your titleImageView as its subview.

UIView *backView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];// Here you can set View width and height as per your requirement for displaying titleImageView position in navigationbar  [backView setBackgroundColor:[UIColor greenColor]]; UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SelectAnAlbumTitleLettering"]]; titleImageView.frame = CGRectMake(45, 5,titleImageView.frame.size.width , titleImageView.frame.size.height); // Here I am passing origin as (45,5) but can pass them as your requirement.  [backView addSubview:titleImageView]; //titleImageView.contentMode = UIViewContentModeCenter; self.navigationItem.titleView = backView; 

Hope it helps you.

like image 28
Nishant Tyagi Avatar answered Sep 30 '22 09:09

Nishant Tyagi


In Swift, you can do it like this:

    var titleView = UIView(frame: CGRectMake(0, 0, 100, 40))
    var titleImageView = UIImageView(image: UIImage(named: "cocolife"))
    titleImageView.frame = CGRectMake(0, 0, titleView.frame.width, titleView.frame.height)
    titleView.addSubview(titleImageView)
    navigationItem.titleView = titleView
like image 45
user3109460 Avatar answered Sep 30 '22 09:09

user3109460