Back Button in navigation controller
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开发者_如何学C)];
}//worked satisfactorily for me
@end
- Create a
UIButton
using your ownUIImage
to mimic the shape you want. - The
UIImage
must be a stretchable type, that is, you would set theleftCapWidth
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
navigationItem
sleftBarButtonItem
property.
The button will automatically size to fit your title.
Use sizeWithFont:
NSString method to calculate the size of the title.
See NSString UIKit Additions Reference
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.
- the text that you want to have in your string.
- 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.
精彩评论