Rason的iOS快速入门专题iOS Developer程序员

iOS --- 自定义navigationBar的两种常见方式

2016-07-27  本文已影响7096人  icetime17

我们经常会有自定义navigationBar的需求, 通常有两种实现方式.

自定义titleView

_imageViewAvatar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 88, 88)];
_imageViewAvatar.layer.cornerRadius = 44;
_imageViewAvatar.layer.masksToBounds = YES;
_imageViewAvatar.image = [UIImage imageNamed:@"avatar.png"];
_imageViewAvatar.center = CGPointMake(titleView.center.x, 22);

UIView *titleView = [[UIView alloc] init];
[titleView addSubview:_imageViewAvatar];

// titleView会自动被系统设置大小.
// 使用imageViewAvatar的大小需要调整
self.navigationItem.titleView = titleView;

效果图:

自定义titleView.png

新建UIView覆盖原来的navigationBar

先将原来的navigationBar隐藏, 再自定义一个UIView覆盖在其上.

self.navigationController.navigationBarHidden = YES;

UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.frame), 44)];
aView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:aView];

UILabel *label = [[UILabel alloc] initWithFrame:aView.bounds];
label.text = @"This is new navigation bar";
label.textAlignment = NSTextAlignmentCenter;
[aView addSubview:label];

注意: 状态栏statusBar的高度为20, 导航栏navigationBar的高度为44.
效果图:

新建UIView覆盖原来的navigationBar.png

Demo

Demo请参考:
DemoNavigationItemAvatar

上一篇下一篇

猜你喜欢

热点阅读