iphone - 如何将标题标签的大小设置为导航栏的全宽

标签 iphone ios objective-c uilabel navbar

我使用下面的代码在导航栏中有一个标题标签。我似乎无法将其调整为全 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 colorWithRed:(219/255.0) green:(52/255.0) blue:(31/255.0) alpha:1] ;
tlabel.adjustsFontSizeToFitWidth=YES;
tlabel.textAlignment = UITextAlignmentCenter;
self.navigationItem.titleView=tlabel;

enter image description here

从 Paras Joshi 更改代码后,右侧正确但左侧偏离。

enter image description here

最佳答案

使用下面的代码,我在 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 colorWithRed:(219/255.0) green:(52/255.0) blue:(31/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/

相关文章:

iphone - 如何找到加载到 Malloc 32kb 中的漏水水龙头

ios - NSMutableAttributedString 不工作 : bold the part of NSString

ios - NSMutableDictionary 增删改 KVO

ios - 使用自定义相机覆盖 View 时底部的黑色 View (UIImagePickerController)

objective-c - setNilValueForKey 错误

iphone - 当 UIScrollview 停止滚动动画时获取标签的值

ios - 后退按钮未出现在 UIViewController 中

ios - 这里是 iOS map distanceToDestination

ios - [NSConcreteValue浮点值] : unrecognized selector sent to instance

ios - UITextField TapGesture 在 iOS 7.1 上没有响应