-->

Custom Nav Title offset ios 11

2019-07-20 15:05发布

问题:

I have a custom navigation item title that is simply two labels, one on top of the other, loaded from a .xib file.

It's loaded by calling this:

class Utilities {
  /// Title and subtitle format custom title in Navigation bar.  Top and bottom text are centered on one another.
  ///
  /// - Parameters:
  ///   - navigationItem: The receiving controller's navigation item.
  ///   - titleText: Top text to be displayed a little larger and more bold.
  ///   - subtitleText: Bottom text to be displayed a little smaller and less bold.
  class func addCustomNavigationTitle(navigationItem: UINavigationItem, titleText: String, subtitleText: String) {
      let customNavigationTitleView =   LabelSubLabelCustomHeaderView.instanceFromNib() as! LabelSubLabelCustomHeaderView
      customNavigationTitleView.titleLabel.text = titleText
      customNavigationTitleView.dateLabel.text = subtitleText
      navigationItem.titleView = customNavigationTitleView
  }
  ...
}

It's defined as this:

class LabelSubLabelCustomHeaderView: UIView {
  @IBOutlet var titleLabel: UILabel!
  @IBOutlet var dateLabel: UILabel!

  class func instanceFromNib() -> UIView {
      return UINib(nibName: "LabelSubLabelCustomHeaderView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
  }
}

Now, it's pushed down by exactly 22 pixels, which hides the bottom label.

I have to set the frame of this view in the viewDidAppear in order to set it straight. I tried viewWillAppear and several other things. I'm literally having to hide it, set it, then show it, which is clearly not right.

Prior to iOS 11, this worked no problem.

Here it is now, without my hack fix, which I hope I can make right:

And here is what it should look like, what it looked like prior to iOS 10, and how it looks with my hack fix:

Also please note that when the unwind segue is animating, the view goes back to the incorrect frame, being 22 pixels too low. How can I fix this? Thanks for any help in advance.

Edit: More detailed constraint info:

回答1:

You should add a layout constraint in your custom view title Xib enforcing a minimum distance between the lower label to the safe area of the view. For a complete working example on iOS 10/11, see https://github.com/ekscrypto/Swift-Tutorial-Custom-Title-View