Customize navigation bar with title view

2019-01-22 06:15发布

I am trying to add a custom view in the center of a navigation bar and I am using the following code to test it:

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

I am setting this up in the viewDidLoad method of my view controller but when i run my program nothing seems to change in my navigation bar.

Could you help me with this?

8条回答
女痞
2楼-- · 2019-01-22 07:12

This works. Give frame at the time of initialisation

 UIView *iv = [[UIView alloc] initWithFrame:CGRectMake(0,0,32,32)];
 [iv setBackgroundColor:[UIColor whiteColor]];
  self.navigationItem.titleView = iv;
查看更多
老娘就宠你
3楼-- · 2019-01-22 07:14

Swift 3/4

You may set i.e. UILabel as a titleView. Call it in viewDidLoad():

private func setNavigationTitle(_ title: String) {
    navigationItem.title = nil // clear the default title
    let titleLabel = UILabel() // you don't need to specify a frame, it will be centred in the navbar
    titleLabel.font = ...
    titleLabel.textColor = ...
    titleLabel.text = title
    titleLabel.backgroundColor = .clear
    navigationItem.titleView = titleLabel
    navigationTitleView = titleLabel // you may create a property if you want to manipulate the title view later
}

Note navigationItem.title = nil, otherwise title may override titleView.

查看更多
登录 后发表回答