UISearchBar 在 iOS 11 中增加导航栏高度

UISearchBar increases navigation bar height in iOS 11

我的 UISearchBar 是导航栏的一部分,例如:

 let searchBar = UISearchBar()
 //some more configuration to the search bar
 .....
 navigationItem.titleView = searchBar

更新到 iOS 11 后,我的应用程序中的搜索栏发生了一些奇怪的事情。在 iOS 10 之前,我的导航栏看起来像:

现在 iOS 11 我有:

如您所见,两个搜索栏的四舍五入有所不同,我并不介意。问题是搜索栏增加了导航栏的高度。所以当我转到另一个控制器时,它看起来也很奇怪:

其实那个奇怪的黑线的高度加上当前导航栏的高度等于第二张图的导航栏高度...

有什么想法可以消除黑线并在所有视图控制器中保持一致的导航栏高度吗?

编辑:@zgjie 的回答是解决这个问题的更好方法:https://whosebug.com/a/46356265/1713123

发生这种情况似乎是因为在 iOS 11 中,SearchBar 的默认高度值更改为 56,而不是之前 iOS 版本中的 44。

目前,我已应用此解决方法,将 searchBar 高度设置回 44:

let barFrame = searchController.searchBar.frame
searchController.searchBar.frame = CGRect(x: 0, y: 0, width: barFrame.width, height: 44)    

另一个解决方案是使用 new searchController property on navigationItem in iOS 11:

navigationItem.searchController = searchController

但这样搜索栏就会出现在导航标题下方。

您可以为 iOS 11.

的搜索栏添加高度 44 的限制条件

// Swift

if #available(iOS 11.0, *) {
    searchBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
}

// Objective-C

if (@available(iOS 11.0, *)) {
    [searchBar.heightAnchor constraintEqualToConstant:44].active = YES;
}

就我而言,更大的 UINavigationBar 高度对我来说不是问题。我只需要重新对齐左右栏按钮项。这就是我想出的解决方案:

- (void)iOS11FixNavigationItemsVerticalAlignment
{
    [self.navigationController.navigationBar layoutIfNeeded];

    NSString * currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:@"11" options:NSNumericSearch] != NSOrderedAscending)
    {
        UIView * navigationBarContentView;
        for (UIView * subview in [self.navigationController.navigationBar subviews])
        {
            if ([subview isKindOfClass:NSClassFromString(@"_UINavigationBarContentView")])
            {
                navigationBarContentView = subview;
                break;
            }
        }

        if (navigationBarContentView)
        {
            for (UIView * subview in [navigationBarContentView subviews])
            {
                if (![subview isKindOfClass:NSClassFromString(@"_UIButtonBarStackView")]) continue;

                NSLayoutConstraint * topSpaceConstraint;
                NSLayoutConstraint * bottomSpaceConstraint;

                CGFloat topConstraintMultiplier = 1.0f;
                CGFloat bottomConstraintMultiplier = 1.0f;

                for (NSLayoutConstraint * constraint in navigationBarContentView.constraints)
                {
                    if (constraint.firstItem == subview && constraint.firstAttribute == NSLayoutAttributeTop)
                    {
                        topSpaceConstraint = constraint;
                        break;
                    }

                    if (constraint.secondItem == subview && constraint.secondAttribute == NSLayoutAttributeTop)
                    {
                        topConstraintMultiplier = -1.0f;
                        topSpaceConstraint = constraint;
                        break;
                    }
                }

                for (NSLayoutConstraint * constraint in navigationBarContentView.constraints)
                {
                    if (constraint.firstItem == subview && constraint.firstAttribute == NSLayoutAttributeBottom)
                    {
                        bottomSpaceConstraint = constraint;
                        break;
                    }

                    if (constraint.secondItem == subview && constraint.secondAttribute == NSLayoutAttributeBottom)
                    {
                        bottomConstraintMultiplier = -1.0f;
                        bottomSpaceConstraint = constraint;
                        break;
                    }
                }

                CGFloat contentViewHeight = navigationBarContentView.frame.size.height;
                CGFloat subviewHeight = subview.frame.size.height;
                topSpaceConstraint.constant = topConstraintMultiplier * (contentViewHeight - subviewHeight) / 2.0f;
                bottomSpaceConstraint.constant = bottomConstraintMultiplier * (contentViewHeight - subviewHeight) / 2.0f;
            }
        }
    }
}

基本上,我们搜索包含条形按钮项的堆栈视图,然后更改它们的顶部和底部约束值。是的,这是一个肮脏的 hack,如果您可以通过任何其他方式解决您的问题,我们不建议您使用它。

我相信 iOS 11 UISearchBar 现在的高度等于 56,而 UINavigationBar 使用自动布局来适应其子视图,因此它增加了高度。如果您仍然希望像 iOS 11 之前那样将 UISearchBar 作为 titleView,我发现最好的方法是将 UISearchBar 嵌入自定义视图中,并将该视图的高度设置为 44,并将其分配给navigationItem.titleView

class SearchBarContainerView: UIView {  

    let searchBar: UISearchBar  

    init(customSearchBar: UISearchBar) {  
        searchBar = customSearchBar  
        super.init(frame: CGRect.zero)  

        addSubview(searchBar)  
    }

    override convenience init(frame: CGRect) {  
        self.init(customSearchBar: UISearchBar())  
        self.frame = frame  
    }  

    required init?(coder aDecoder: NSCoder) {  
        fatalError("init(coder:) has not been implemented")  
    }  

    override func layoutSubviews() {  
        super.layoutSubviews()  
        searchBar.frame = bounds  
    }  
}  

class MyViewController: UIViewController {  

    func setupNavigationBar() {  
        let searchBar = UISearchBar()  
        let searchBarContainer = SearchBarContainerView(customSearchBar: searchBar)  
        searchBarContainer.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)  
        navigationItem.titleView = searchBarContainer  
    }  
} 

在Objective-C

if (@available(iOS 11.0, *)) {
        [self.searchBar.heightAnchor constraintLessThanOrEqualToConstant: 44].active = YES;
}              

我尝试了各种方法使大小恢复到原来的 44,但是搜索栏看起来和行为总是很奇怪 - 比如被拉得太远,y 轴偏移等等。

我在这里找到了一个很好的解决方案(通过其他一些 Whosebug post): https://github.com/DreamTravelingLight/searchBarDemo

只需从 SearchViewController 派生您的 viewcontroller 并在您的项目中包含 SearchViewController 和 WMSearchbar 类。如果 (iOS11) else... 丑陋,对我来说开箱即用,没有任何丑陋。

//
//  Created by Sang Nguyen on 10/23/17.
//  Copyright © 2017 Sang. All rights reserved.
//

import Foundation
import UIKit

class CustomSearchBarView: UISearchBar {
    final let SearchBarHeight: CGFloat = 44
    final let SearchBarPaddingTop: CGFloat = 8
    override open func awakeFromNib() {
        super.awakeFromNib()
        self.setupUI()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
       // fatalError("init(coder:) has not been implemented")
    }
    func findTextfield()-> UITextField?{
        for view in self.subviews {
            if view is UITextField {
                return view as? UITextField
            } else {
                for textfield in view.subviews {
                    if textfield is UITextField {
                        return textfield as? UITextField
                    }
                }
            }
        }
        return nil;
    }
    func setupUI(){
        if #available(iOS 11.0, *) {
            self.translatesAutoresizingMaskIntoConstraints = false
            self.heightAnchor.constraint(equalToConstant: SearchBarHeight).isActive = true
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        if #available(iOS 11.0, *) {
            if let textfield = self.findTextfield() {
                textfield.frame = CGRect(x: textfield.frame.origin.x, y: SearchBarPaddingTop, width: textfield.frame.width, height: SearchBarHeight - SearchBarPaddingTop * 2)`enter code here`
                return
            }
        }
    }
}

所有解决方案都不适合我,所以在我推送视图控制器之前我做了:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    self.navigationItem.titleView = UIView()
}

返回时显示搜索栏:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationItem.titleView = UISearchBar()
}

我发现麦麦的解决方案是唯一真正可用的解决方案。
然而它仍然不完美:
旋转设备时,搜索栏未正确调整大小并保持在较小的尺寸。

我已经找到了解决办法。这是我在 Objective C 中的代码,相关部分已注释:

// improvements in the search bar wrapper
@interface SearchBarWrapper : UIView
@property (nonatomic, strong) UISearchBar *searchBar;
- (instancetype)initWithSearchBar:(UISearchBar *)searchBar;
@end
@implementation SearchBarWrapper
- (instancetype)initWithSearchBar:(UISearchBar *)searchBar {
    // setting width to a large value fixes stretch-on-rotation
    self = [super initWithFrame:CGRectMake(0, 0, 4000, 44)];
    if (self) {
        self.searchBar = searchBar;
        [self addSubview:searchBar];
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.searchBar.frame = self.bounds;
}
// fixes width some cases of resizing while search is active
- (CGSize)sizeThatFits:(CGSize)size {
    return size;
}
@end

// then use it in your VC
@implementation MyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.titleView = [[SearchBarWrapper alloc] initWithSearchBar:self.searchController.searchBar];
}
@end

现在还有一例没弄明白。要重现,请执行以下操作:
- 以纵向开始
- 激活搜索字段
- 旋转到横向
- 错误:栏未调整大小

在 "ACKNOWLEDGEMENTS" 视图控制器上尝试此代码 在 viewDidLoad

self.extendedLayoutIncludesOpaqueBars = true

我无法使用将导航栏保持在 44 的解决方案。 所以我花了一天时间,但最后,我找到了一个解决方案,它不会改变栏的高度并将按钮放在栏的中间。问题是按钮放置在配置为水平堆栈视图的堆栈视图中,因此不会根据高度变化进行调整。

这是在初始化时完成的:

UIBarButtonItem *cancelButton;
if (@available(iOS 11.0, *)) {
    // For iOS11 creating custom button to accomadate the change of navbar + search bar being 56 points
    self.navBarCustomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.navBarCustomButton setTitle:@"Cancel"];
    [self.navBarCustomButton addTarget:self action:@selector(cancelButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    cancelButton = [[UIBarButtonItem alloc] initWithCustomView:self.navBarCustomButton];
} else {
    cancelButton = [[UIBarButtonItem alloc] initWithTitle:MagicLocalizedString(@"button.cancel", @"Cancel")
                                                                                         style:UIBarButtonItemStylePlain
                                                                                        target:self
                                                                                        action:@selector(cancelButtonTapped)];
}

在 viewWillApear 上(或视图添加到导航堆栈后的任何时间)

   if (@available(iOS 11.0, *)) {
        UIView *buttonsStackView = [navigationController.navigationBar subviewOfClass:[UIStackView class]];
        if (buttonsStackView ) {
            [buttonsStackView.centerYAnchor constraintEqualToAnchor:navigationController.navigationBar.centerYAnchor].active = YES;
            [self.navBarCustomButton.heightAnchor constraintEqualToAnchor:buttonsStackView.heightAnchor];
        }
    }

而 subviewOfClass 是 UIView 上的一个类别:

- (__kindof UIView *)subviewOfClass:(Class)targetClass {
     // base case
     if ([self isKindOfClass:targetClass]) {
        return self;
     }

     // recursive
    for (UIView *subview in self.subviews) {
        UIView *dfsResult = [subview subviewOfClass:targetClass];

        if (dfsResult) {
           return dfsResult;
       }
   }
   return nil;
}

在我的例子中,我必须将 textField 的高度降低 36pt -> 28pt。

所以我尝试改变框架的高度,图层的高度。但是方法没有用。

最后,我找到了一个解决方案,那就是面具。 我认为,这不是一个好方法,但它有效。

    let textField              = searchBar.value(forKey: "searchField") as? UITextField
    textField?.font            = UIFont.systemFont(ofSize: 14.0, weight: .regular)
    textField?.textColor       = #colorLiteral(red: 0.1960784314, green: 0.1960784314, blue: 0.1960784314, alpha: 1)
    textField?.textAlignment   = .left

    if #available(iOS 11, *) {
        let radius: CGFloat           = 5.0
        let magnifyIconWidth: CGFloat = 16.0
        let inset                     = UIEdgeInsets(top: 4.0, left: 0, bottom: 4.0, right: 0)

        let path = CGMutablePath()
        path.addArc(center: CGPoint(x: searchBar.bounds.size.width - radius - inset.right - magnifyIconWidth, y: inset.top + radius), radius: radius, startAngle: .pi * 3.0/2.0, endAngle: .pi*2.0, clockwise: false)                        // Right top
        path.addArc(center: CGPoint(x: searchBar.bounds.size.width - radius - inset.right - magnifyIconWidth, y: searchBar.bounds.size.height - radius - inset.bottom), radius: radius, startAngle: 0, endAngle: .pi/2.0, clockwise: false)  // Right Bottom
        path.addArc(center: CGPoint(x: inset.left + radius, y: searchBar.bounds.size.height - radius - inset.bottom), radius: radius, startAngle: .pi/2.0, endAngle: .pi, clockwise: false)                                                  // Left Bottom
        path.addArc(center: CGPoint(x: inset.left + radius, y: inset.top + radius),  radius: radius, startAngle: .pi, endAngle: .pi * 3.0/2.0, clockwise: false)                                                                             // Left top

        let maskLayer      = CAShapeLayer()
        maskLayer.path     = path
        maskLayer.fillRule = kCAFillRuleEvenOdd

        textField?.layer.mask = maskLayer
    }

如果您想更改文本字段的框架,您可以更改插图。

在两种情况下,iOS11 中的 NavigationBar 和 SearchBar 下出现黑线:

  • 当我使用 UISearchBar 从 ViewController 推送另一个 ViewController 时

  • 当我用 "drag right to dismiss" 用 UISearchBar 解雇了 ViewController

我的解决方案是:将此代码添加到我的 ViewController with UISearchBar:

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.view setNeedsLayout]; // force update layout
    [self.navigationController.view layoutIfNeeded]; // to fix height of the navigation bar
}

Swift 4 次更新

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.view.setNeedsLayout() // force update layout
    navigationController?.view.layoutIfNeeded() // to fix height of the navigation bar
}

我通过在嵌入搜索栏的地图视图控制器上向 viewDidAppear 添加约束来修复此问题

public override func viewDidAppear(_ animated: Bool) {
    if #available(iOS 11.0, *) {

        resultSearchController?.searchBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
        // searchBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
    }
}

你所要做的就是继承 UISearchBar 并覆盖 "intrinsicContentSize":

@implementation CJSearchBar
-(CGSize)intrinsicContentSize{
    CGSize s = [super intrinsicContentSize];
    s.height = 44;
    return s;
}
@end

谢谢大家!我终于找到了解决办法。

使用 UISearchBar 将以下代码添加到 ViewController。

  1. 第一步:viewDidLoad
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    ...
}
override func viewDidLoad() {
    super.viewDidLoad()
    self.extendedLayoutIncludesOpaqueBars = true
}
  1. 第二步:viewWillDisappear
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
     // force update layout
    [self.navigationController.view setNeedsLayout]; 
    // to fix height of the navigation bar
    [self.navigationController.view layoutIfNeeded];  
}
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.view.setNeedsLayout() // force update layout
        navigationController?.view.layoutIfNeeded() // to fix height of the navigation bar
    }

您好使用 UISearchController 并将其 UISearchBar 附加到 navigationItem.titleView 的人。我每天疯狂地花 4-5 个小时来解决这个问题。按照 iOS 11+ 推荐的方法,将 searchController 放在 navigation.searchController 上并不适合我的情况。具有此 searchController/searchBar 的屏幕有一个自定义的后退按钮。

我已经在 iOS 10、iOS 11 和 12 中进行了测试。在不同的设备中。我只是不得不。不解决这个恶魔我就不能回家。鉴于我的最后期限很紧,这是我今天能做的最完美的事情。

所以我只想分享我所做的这项艰苦工作,将所有内容放入您想要的位置取决于您(例如 viewModel 中的变量)。开始了:

在我的第一个屏幕(比如主屏幕,没有这个搜索控制器)中,我的 viewDidLoad().

中有这个
self.extendedLayoutIncludesOpaqueBars = true

在我的第二个屏幕中,那个有 searchController 的屏幕,我在我的 viewDidAppear 中有这个。

override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(动画)

    let systemMajorVersion = ProcessInfo.processInfo.operatingSystemVersion.majorVersion
    if systemMajorVersion < 12 {
        // Place the search bar in the navigation item's title view.
        self.navigationItem.titleView = self.searchController.searchBar
    }

    if systemMajorVersion >= 11 {

        self.extendedLayoutIncludesOpaqueBars = true

        UIView.animate(withDuration: 0.3) {
            self.navigationController?.navigationBar.setNeedsLayout()
            self.navigationController?.navigationBar.layoutIfNeeded()
        }

        self.tableView.contentInset = UIEdgeInsets(top: -40, left: 0, bottom: 0, right: 0)

        if self.viewHadAppeared {
            self.tableView.contentInset = .zero
        }
    }

    self.viewHadAppeared = true // this is set to false by default.
}

这是我的 searchController 声明:

lazy var searchController: UISearchController = {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.textField?.backgroundColor = .lalaDarkWhiteColor
    searchController.searchBar.textField?.tintColor = .lalaDarkGray
    searchController.searchBar.backgroundColor = .white
    return searchController
}()

所以我希望有一天这对某人有所帮助。

无法发表评论,但想分享一些我 运行 遇到的其他问题,同时即使在使用其他解决方案之一后,我仍会花费大量时间试图查明此问题的根源。

看来对我来说最好的解决方法是 :

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.view.setNeedsLayout() // force update layout
    navigationController?.view.layoutIfNeeded() // to fix height of the navigation bar
}

但是,至少 在 iOS 12.1,如果您的 UINavigationBar:

  • 已将 isTranslucent 设置为 false,带有搜索栏的视图控制器在交互式关闭时似乎无法调整其视图布局(通过后退按钮正常关闭似乎有效)。
  • 它的背景图像使用setBackgroundImage(UIImage(), for: .default)设置,t运行sition 动画不能正常工作,完成后会跳回到它的位置。

这些特定的属性被设置为让导航栏以某种方式出现,所以我需要做一些调整来恢复它,或者忍受奇怪的行为。如果我 运行 进入其他任何内容或找到其他解决方案或其他 OS 版本中的差异,我会尽量记住更新以上内容。

这也发生在我身上,所有 运行 在 iOS 12.4 中都很好,而在上面的 13 中变得很奇怪。 问题出在 iOS 13 从实现 searchBar 的 UIViewController 跳转后,导航栏高度从 88 增加到 100。

在实现 searchBar 的 UIViewController 中试试这个。

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.view.setNeedsLayout()
    navigationController?.view.layoutIfNeeded()
}

修复后预览:

修复前预览: