0
votes

Its a very basic question - but i could not find the answer to it anywhere. I would like a back button like the default one that shows up in a navigation bar, but with a image in the background. Even with customization, how to calculate the size/length of the button as per the title? Thanks a ton for the help,in advance!

UPDATE:

Thanks guys! but the answer that i finally implemented was this:

@implementation UINavigationBar (UINavigationBarCategory)

-(void)drawRect:(CGRect)rect

{

UIColor *color = [UIColor colorWithRed:(13.0/255.0) green:(183.0/255.0) blue:(255.0/255.0) alpha:1.0];

// use a custom color for the back button which i got using the digital color meter on my nav bar image :P

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetFillColor(context, CGColorGetComponents( [color CGColor]));

CGContextFillRect(context, rect);
self.tintColor = color;
// use a custom background image for my navigation bar

UIImage *img = [UIImage imageNamed: Navigation_img];

[img drawInRect:CGRectMake(0,0,img.size.width,img.size.height)];

}//worked satisfactorily for me

@end

3
The above answer just incorporates a color to the default back button in a navigation item along with a background image to the navigation bar.Prathiba

3 Answers

0
votes
  • Create a UIButton using your own UIImage to mimic the shape you want.
  • The UIImage must be a stretchable type, that is, you would set the leftCapWidth to be the size of your back arrow
  • Set the UIButton's title to whatever you like
  • Create a new UIBarButtonItem using your new button as a custom view
  • Set this to your navigationItems leftBarButtonItem property.

The button will automatically size to fit your title.

0
votes

Use sizeWithFont: NSString method to calculate the size of the title.

See NSString UIKit Additions Reference

0
votes

To find out the width of specific text, you may use following methods.

 NSString *str=@"Back";

CGSize sizeOfBack = [str sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(30, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];

Let me explain above two statements.

  1. the text that you want to have in your string.
  2. sizewithfont method will allow you to calculate the size.

Here, sizeOfBack.width will give me the width acquired by 14System sized string.

Hope it helps to you. let me know by comments, if you have yet doubts regarding this.