我们怎样才能在iOS中的UInavigationBar插入多个标题

您好我是iOS的初学者,在我的项目中,我需要在UInavigationBar的“左侧中心”和“右侧中心”插入“标题”,如下图所示,请帮助我如何做到我的要求

在这里输入图像说明

看下面的代码,并尝试:

- (void)viewDidLoad { [super viewDidLoad]; CGRect frame = [[UIScreen mainScreen] bounds]; UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width/2, 44)]; lbl1.backgroundColor = [UIColor redColor]; lbl1.textAlignment = NSTextAlignmentCenter; lbl1.text = @"Dashboard"; [self.navigationController.navigationBar addSubview:lbl1]; UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(frame.size.width/2, 0, frame.size.width/2, 44)]; lbl2.backgroundColor = [UIColor redColor]; lbl2.textAlignment = NSTextAlignmentCenter; lbl2.text = @"Profile"; [self.navigationController.navigationBar addSubview:lbl2]; } 

您可以自定义导航栏的titleView 。 在这里阅读官方文档 。

根据你的问题,我尝试了下面的工作代码: –

 -(UIView *)getTitleView { CGRect frame = [[UIScreen mainScreen] bounds]; UIView *viewTitle = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, self.navigationController.navigationBar.frame.size.height)]; UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width/2, self.navigationController.navigationBar.frame.size.height)]; lbl1.backgroundColor = [UIColor colorWithRed:130/255.0f green:13/255.0f blue:23/255.0f alpha:1.0f]; lbl1.textAlignment = NSTextAlignmentCenter; [lbl1 setTextColor:[UIColor whiteColor]]; lbl1.text = @"Dashboard"; [viewTitle addSubview:lbl1]; UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(frame.size.width/2, 0, frame.size.width/2, viewTitle.frame.size.height)]; lbl2.backgroundColor = [UIColor colorWithRed:130/255.0f green:13/255.0f blue:23/255.0f alpha:1.0f]; [lbl2 setTextColor:[UIColor whiteColor]]; lbl2.textAlignment = NSTextAlignmentCenter; lbl2.text = @"Profile"; [viewTitle addSubview:lbl2]; return viewTitle; } - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.titleView = [self getTitleView]; } 

我将代码分成单独的方法来遵循模块化的方法 。 对于任何分开的任务代码部分,用不同的方法编写这段代码。 这将导致更多的可读性。