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

本文介绍两种自定义NavigationBar的方法:一是通过自定义titleView实现,二是通过新建UIView覆盖原navigationBar实现。这两种方法均可帮助开发者灵活定制应用界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

效果图:
这里写图片描述

新建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.
效果图:
这里写图片描述

Demo

Demo请参考:
DemoNavigationItemAvatar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值