自定义带标题视图的导航栏

Jul*_*rio 33 objective-c uinavigationbar uinavigationitem ios swift

我试图在导航栏的中心添加自定义视图,我正在使用以下代码来测试它:

UIView * testView = [[UIView alloc] init];
[testView setBackgroundColor:[UIColor blackColor]];
testView.frame = CGRectMake(0, 0, 100, 35);
[self.navigationController.navigationItem.titleView addSubview:testView];
Run Code Online (Sandbox Code Playgroud)

我在我的视图控制器的viewDidLoad方法中进行设置,但是当我运行我的程序时,我的导航栏中似乎没有任何变化.

你能帮帮我吗?

vir*_*ata 68

这有效.在初始化时给出帧

 UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
 [iv setBackgroundColor:[UIColor whiteColor]];
  self.navigationItem.titleView = iv;
Run Code Online (Sandbox Code Playgroud)

  • 是的,就是这样!非常感谢!我可以问你为什么我不能使用以下方法访问导航项:"self.navigationController.navigationItem.titleView"从导航控制器访问导航项是错误的.非常感谢@virata (3认同)
  • @JulianOsorio这不是关于`self.navigationItem.titleView`和`self.navigationController.navigationItem.titleView`的问题,它是`addSubview`和`setTitleView`之间的区别.:) (3认同)
  • 很奇怪,它在iOS 7上不起作用..我添加了一个searchBar ..我得到关于autolayout东西的投诉.. (2认同)

Rap*_*ira 34

如果您只想为一个视图控制器自定义标题,则可以使用

UILabel *lblTitle = [[UILabel alloc] init];
lblTitle.text = @"Diga-nos o motivo";
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor colorWithRed:77.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0];
lblTitle.shadowColor = [UIColor whiteColor];
lblTitle.shadowOffset = CGSizeMake(0, 1);
lblTitle.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0];
[lblTitle sizeToFit];

self.navigationItem.titleView = lblTitle;
Run Code Online (Sandbox Code Playgroud)

或者如果要为所有视图控制器使用自定义

[[UINavigationBar appearance] setTitleTextAttributes:
    [NSDictionary dictionaryWithObjectsAndKeys:
        [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0], 
        UITextAttributeTextColor, 
        [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8], 
        UITextAttributeTextShadowColor, 
        [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], 
        UITextAttributeTextShadowOffset, 
        [UIFont fontWithName:@"Arial-Bold" size:10.0], 
        UITextAttributeFont, 
        nil]];
Run Code Online (Sandbox Code Playgroud)


Kju*_*uly 26

更换

[self.navigationController.navigationItem.titleView addSubview:testView];
Run Code Online (Sandbox Code Playgroud)

self.navigationItem.titleView = testView;
Run Code Online (Sandbox Code Playgroud)

编辑:

注意:您无法将子视图添加到titleView,因为它的默认值是nil,您需要将新视图设置为titleView.