重載 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

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM