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];
[
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;
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
.