iOS开发之UINavigationBar(一)

来源:互联网 发布:安卓手机微信数据恢复 编辑:程序博客网 时间:2024/06/06 05:12

本文主要介绍一下UINavigationBar的简单使用和一些属性、方法。下面通过代码来讲解。新建项目,使得主窗口的根视图是导航栏控制器,这里导航栏控制器的主视图是HXMainViewController。

导航栏高度默认:44。自iOS7.0之后,控制器的状态栏也是导航栏的一部分,即导航栏部分44 + 20,

首先来设置导航栏上的左右按钮

    // 在导航条上添加左右按钮    // 左边    UIBarButtonItem *hahaItem = [[UIBarButtonItem alloc] initWithTitle:@"哈哈" style:UIBarButtonItemStylePlain target:nil action:nil];    UIBarButtonItem *xixiItem = [[UIBarButtonItem alloc] initWithTitle:@"嘻嘻" style:UIBarButtonItemStyleDone target:nil action:nil];        // 设置单个按钮//    self.navigationItem.leftBarButtonItem = hahaItem;        // 设置多个按钮    self.navigationItem.leftBarButtonItems = @[hahaItem, xixiItem];            // 右边    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:nil action:nil];    // 设置单个按钮//    self.navigationItem.rightBarButtonItem = addItem;        // 设置多个按钮    self.navigationItem.rightBarButtonItems = @[addItem, searchItem];
以上设置的导航栏按钮都是利用系统自带的按钮设置,下面设置自定义的按钮

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];    button.backgroundColor = [UIColor redColor];    [button setTitle:@"自定义按钮" forState:UIControlStateNormal];    button.frame = CGRectMake(0, 0, 100, 44);    // 当自定义导航栏上的子控件时,控件的位置设置就没有效果    UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];    self.navigationItem.leftBarButtonItem = customItem;        // 当自定义导航栏左侧或右侧按钮时,位置可能不是自己想要的,可以进行如下设置(两种方法)    // 1.设置固定宽度的FixedSpace样式的item//    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];//    <span style="color:#FF0000;">spaceItem.width = -10;</span>// 让FixedSpace样式的item宽度为-10,这样就可以让customItem向左靠近//    self.navigationItem.leftBarButtonItems = @[spaceItem, customItem];            // 2.设置控件的内容边距    button.contentEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0);    // 也可以设置成向左靠近的效果,右边的控件也可以同样设置
导航栏不仅可以设置左右控件,还可以设置中间控件(标题),利用titleView属性

// 设置头部标题//    self.title = @"Main";// 可同时设置头部标题和tabBar(标签按钮)上的标题    self.navigationItem.title = @"Main";        // 设置标题控件    self.navigationItem.titleView = [UIButton buttonWithType:UIButtonTypeContactAdd];
设置导航栏自身的一些属性

    // 设置导航栏背景颜色//    self.navigationController.navigationBar.tintColor = [UIColor redColor];// iOS7.0之前有效,iOS7.0之后没有效    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];// iOS7.0之后有效    // 隐藏导航栏    self.navigationController.navigationBar.hidden = YES;//    self.navigationController.navigationBarHidden = YES;

下面对UINavigationBar上的结构做一个简单的图例,如下:


0 0
原创粉丝点击