iOS导航栏主题

主要是取得导航栏的appearance对象,操作它就设置导航栏的主题

UINavigationBar *navBar = [UINavigationBar appearance];

 

常用主题设置

导航栏背景

- (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics;

标题

@property(nonatomic,copy) NSDictionary *titleTextAttributes;

// 字典中能用到的key在UIStringDrawing.h中

// 最新版本的key在UIKit框架的NSAttributedString.h中

 

iOS7返回按钮的箭头样式

@property(nonatomic,retain) UIColor *tintColor;

 

导航栏的左上角和右上角都是UIBarButtonItem对象,为了统一样式,也可以设置的UIBarButtonItem主题

UIBarButtonItem *item = [UIBarButtonItem appearance];

 

设置主题的方法

背景

- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;

 

文字

- (void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state;

 

导航栏返回按钮背景

- (void)setBackButtonBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;

 

iOS6导航栏背景的出图规格

非retina:320x44 px

retina:640x88 px

 

iOS7导航栏背景的出图规格

retina:640x128 px

 

自定义导航控制器

自定义导航控制器的步骤:新建一个类,继承自UINavigationController

 

自定义导航控制器的价值

重写push方法就可以拦截所有压入栈中的子控制器,统一做一些处理

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;

 

重写pop方法就可以拦截所有子控制器的出栈

- (UIViewController *)popViewControllerAnimated:(BOOL)animated;

 

为了在push控制器时隐藏UITabBar,需要做以下设置

viewController.hidesBottomBarWhenPushed = YES;

 

initailize、load方法的区别

initailize、load都是类方法

当一个类被装载进内存时,就会调用一次load方法(当时这个类还不可用)

当第一次使用这个类时,就会调用一次initailize方法

 

程序启动完毕后再显示回状态栏(前提是状态栏交给了UIApplication管理)

application.statusBarHidden = NO;

UIImaegView的图片拉伸可以通过storyboard或者xib设置

UIButton不能通过storyboard或者xib设置,必须通过代码

swift中设置导航栏主题的做法:

   func setupnav(){

        let navbar = UINavigationBar.appearance() // 获取导航栏的appearance对象

        navbar.barTintColor = barTintColor

        let navbartitleDict:NSDictionary = [NSForegroundColorAttributeName:navtextcolor,NSFontAttributeName: UIFont.systemFontOfSize(18)]

        navbar.titleTextAttributes = navbartitleDict as? [String : AnyObject];

        navbar.tintColor = navtextcolor

        navbar.setBackgroundImage(UIImage(named: "daohang"), forBarMetrics: UIBarMetrics.Default)

     

 

        //去除返回按钮文本

        UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: UIBarMetrics.Default)

        let leftDict:NSDictionary = [NSForegroundColorAttributeName:navtextcolor,NSFontAttributeName: UIFont.systemFontOfSize(15)]

        

        UIBarButtonItem.appearance().setTitleTextAttributes(leftDict as? [String : AnyObject], forState: UIControlState.Normal)

        

    }

导航栏标题不居中问题:

导航栏标题之所以不居中是因为返回的标题太长造成的,只需要把返回按钮的标题修改一下即可

 self.navigationController?.navigationBar.topItem?.title = "";

但是要注意上一级页面需要在viewWillAppear中重新设置一下导航栏的标题

   override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)

        self.navigationItem.title = ""

        

    }

原文地址:https://www.cnblogs.com/sunyaxue/p/4358830.html