https://github.com/YouXianMing

重载 UINavigationController 设置左侧返回按钮的文字为图片

UINavigationController

导航栏控制器的左侧返回按钮如果需要设置成图片,仅使用系统的是无法实现的,需要重载系统的导航栏控制器,在控制器推出之前替换掉leftBarButtonItem才行.

注:以下链接的这个哥们对NavigationViewController所有能做的定制都解说了

http://beyondvincent.com/blog/2013/11/03/120-customize-navigation-status-bar-ios-7/#5

源码如下:

CustomNavigationViewController.h + CustomNavigationViewController.m

 

#import <UIKit/UIKit.h>

@interface CustomNavigationViewController : UINavigationController

@end

 

#import "CustomNavigationViewController.h"

#pragma mark - 支持ARC与非ARC
#if __has_feature(objc_arc)
#define RELEASE(obj)
#define AUTO_RELEASE(obj)
#else
#define Release(obj)      [obj release]
#define Autorelease(obj)  [obj autorelease]
#endif

//判断是否是iOS7
#define iOS7 \
([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)

@interface CustomNavigationViewController ()

@end

@implementation CustomNavigationViewController

#pragma mark - 重载父类进行改写
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    //先进入子Controller
    [super pushViewController:viewController animated:animated];
    
    //替换掉leftBarButtonItem
    if (viewController.navigationItem.leftBarButtonItem== nil && [self.viewControllers count] > 1) {
        viewController.navigationItem.leftBarButtonItem =[self customLeftBackButton];
    }
}

#pragma mark - 自定义返回按钮图片
-(UIBarButtonItem*)customLeftBackButton{
    
    UIImage *image = [UIImage imageNamed:@"back.png"];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    backButton.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    
    [backButton setBackgroundImage:image
                          forState:UIControlStateNormal];
    
    [backButton addTarget:self
                   action:@selector(popself)
         forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    Autorelease(backItem);
    
    return backItem;
}

#pragma mark - 返回按钮事件(pop)
-(void)popself
{
    [self popViewControllerAnimated:YES];
}

#pragma mark - 用图片设置导航背景
+ (void)initialize
{
    //取出设置主题的对象
    UINavigationBar *navBar = [UINavigationBar appearance];
    
    //设置导航栏的背景图片
    NSString *navBarBg = nil;
    if (iOS7)
    {
        navBarBg = @"NavBar64";
        navBar.tintColor = [UIColor whiteColor];
    }
    else
    {
        navBarBg = @"NavBar";
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    }
    [navBar setBackgroundImage:[UIImage imageNamed:navBarBg] forBarMetrics:UIBarMetricsDefault];
    
    //标题颜色
    [navBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
}

@end

 

 

 

 

 

posted @ 2014-03-21 10:12  YouXianMing  阅读(2980)  评论(1编辑  收藏  举报