-->

iOS 11 Navigation TitleView misplaced

2019-01-25 16:07发布

问题:

I have an iOS app in which I am setting a custom navigation title view.

It was working fine till iOS 10, but in iOS 11 the navigation title view is misplaced.

Here is the screen shot for iOS 10 -

Here is the screen shot for iOS 11 -

As you can see in the screen shots that when I run the code on iOS 10 the title view appears to be fine. But the same code on iOS 11 shifts the title view down by some pixels and it gets cut.

This is how I am setting the title view -

navigationItem.titleView = MY_CUSTOM_TITLE_VIEW

I tried many things and searched for many solutions but nothing is working.

回答1:

Here's how it can be fixed -

Add this code in the custom title view class -

override var intrinsicContentSize: CGSize {
    return UILayoutFittingExpandedSize
}

And the custom title view shows up at the correct position.



回答2:

There are problem with new Navigation Bar for iOS, when you add custom view into title view. So, you just add "prefertsLargeTitles" is No & "largeTitleDisplayMode" is DisplayModeNever before implement navigation bar custom.

Here my code :

if (@available(iOS 11.0, *)) {
    [[self navigationController] navigationBar].prefersLargeTitles = NO;
    [[self navigationController] navigationItem].largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeNever;
    }
    // Add contraints to titleView
    NSLayoutConstraint *centerPrompt= [NSLayoutConstraint constraintWithItem:midPromptLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:midView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *topPrompt= [NSLayoutConstraint constraintWithItem:midPromptLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:midView attribute:NSLayoutAttributeTop multiplier:1.0 constant:10];
    NSLayoutConstraint *centerTitle= [NSLayoutConstraint constraintWithItem:midTitleLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:midView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *topTitle= [NSLayoutConstraint constraintWithItem:midTitleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:midPromptLabel attribute:NSLayoutAttributeTop multiplier:1.0 constant:10];

    [midView addConstraints:@[centerPrompt,topPrompt,centerTitle,topTitle]];

Hope will help you ^_^