Search code examples
cocoa-touchuinavigationbarconstraintsautolayouttitleview

Autoresize titleView in a NavigationBar with autolayout


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


Solution

  • 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