美文网首页Rason的iOS快速入门专题iOS Developer程序员
iOS --- 自定义navigationBar的两种常见方式

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

作者: icetime17 | 来源:发表于2016-07-27 22:25 被阅读7096次

我们经常会有自定义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

相关文章

网友评论

  • 任梦RM:第一种在iOS11上超出导航栏的会被截掉不显示了
  • 梁森的简书:有了iPhoneX之后哪种方式更好呢?
  • 603f2dbc9aaf:iphone X出来之后自定义的都跑偏了
  • 85320787afaa:请问一下 可不可以不隐藏原来的navigationBar 直接在navigationBar上addsubView一个全新的View:wink:
    paydrin:  那你这样就不用自定义navigationBar了,自定义就是为了脱离之前的navigationBar。

本文标题:iOS --- 自定义navigationBar的两种常见方式

本文链接:https://www.haomeiwen.com/subject/ujtajttx.html