Autoresize titleView in a NavigationBar with autolayout

5.8k views Asked by At

I want a custom UIView in my UINavigationBar between a left and a right BarButtonItem but as wide as possible. For this reason I added a UIView in IB to the NavigationBar. With autolayout disabled everything works as expected with the autoresizing masks. But in my storyboard with autolayout enabled I just cann't get it to work. It doesn't look like I can set any constraints in IB for the titleView. If I rotate my device to landscape mode, the UIView has still the same width. What do I have to do so that the titleView fills the space between my UIBarButtonItems with autolayout enabled?

Thank you for any help

Linard

2

There are 2 answers

0
Linard Arquint On BEST ANSWER

I solved the issue as following in my code:

 - (void)willAnimateRotationToInterfaceOrientation:(__unused UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
 {
 [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    CGSize navigationBarSize = self.navigationController.navigationBar.frame.size;
    UIView *titleView = self.navigationItem.titleView;
    CGRect titleViewFrame = titleView.frame;
    titleViewFrame.size = navigationBarSize;
    self.navigationItem.titleView.frame = titleViewFrame;
 }

I haven't found another solution (with automatic resizing), but I'm open for new and/or better solutions

Linard

3
ma11hew28 On

You can add constraints in code.

In viewDidLoad, you can do something like this:

UIView *titleView = [[UIView alloc] initWithFrame:CGRectZero];
self.navigationItem.titleView = titleView;
UIView *titleViewSuperview = titleView.superview;
titleView.translatesAutoresizingMaskIntoConstraints = NO;
[titleViewSuperview addConstraint:[NSLayoutConstraint constraintWithItem:titleView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:titleViewSuperview attribute:NSLayoutAttributeLeading multiplier:1 constant:0]]; // leading
[titleViewSuperview addConstraint:[NSLayoutConstraint constraintWithItem:titleView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:titleViewSuperview attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; // top
[titleViewSuperview addConstraint:[NSLayoutConstraint constraintWithItem:titleViewSuperview attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:titleView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]]; // width
[titleViewSuperview addConstraint:[NSLayoutConstraint constraintWithItem:titleViewSuperview attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:titleView attribute:NSLayoutAttributeHeight multiplier:1 constant:0]]; // height