OGeek|极客世界-中国程序员成长平台

标题: iphone - 如何将标题标签调整为导航栏的全宽 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:15
标题: iphone - 如何将标题标签调整为导航栏的全宽

我使用下面的代码在导航栏中有一个标题标签。我似乎无法将其调整到完整 View 的宽度。知道如何解决这个问题吗?

我认为 self.view.bounds.size.width 会将其调整为 View 的整个宽度。

这是我的导航栏标题标签代码,还有一个屏幕截图可以直观地显示问题。

感谢您的帮助

 UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, self.view.bounds.size.width, 48)];
tlabel.text=self.navigationItem.title;
tlabel.text = @"someText"; 
tlabel.font = [UIFont fontWithName"DIN-Bold" size:20];
tlabel.textColor=[UIColor whiteColor];
tlabel.backgroundColor = [UIColor colorWithRed219/255.0) green52/255.0) blue31/255.0) alpha:1] ;
tlabel.adjustsFontSizeToFitWidth=YES;
tlabel.textAlignment = UITextAlignmentCenter;
self.navigationItem.titleView=tlabel;

enter image description here

从 Paras Joshi 更改代码后,右侧是正确的,但左侧是关闭的。

enter image description here



Best Answer-推荐答案


使用下面的代码,我在 UIView 中添加了 UILabel,然后将该 View 设置为 titleView...

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 48)];
UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 320, 48)];
tlabel.text=self.navigationItem.title;
tlabel.text = @"someText"; 
tlabel.font = [UIFont fontWithName"DIN-Bold" size:20];
tlabel.textColor=[UIColor whiteColor];
tlabel.backgroundColor = [UIColor colorWithRed219/255.0) green52/255.0) blue31/255.0) alpha:1] ;
tlabel.textAlignment = UITextAlignmentCenter;   
[headerView addSubview:tlabel];
self.navigationItem.titleView = headerView;

或添加为如下所示的 subview 。

[self.navigationController.navigationBar addSubview:tlabel];

关于iphone - 如何将标题标签调整为导航栏的全宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18014727/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4