试试这个,在我身边工作正常
private var search = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
search.searchBar.delegate = self
search.searchBar.sizeToFit()
search.obscuresBackgroundDuringPresentation = false
search.hidesNavigationBarDuringPresentation = true
self.definesPresentationContext = true
search.searchBar.placeholder = "Search here"
self.navigationItem.searchController = search
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.hidesSearchBarWhenScrolling = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationItem.hidesSearchBarWhenScrolling = true
}
对于大型导航栏使用这个
如需完整的应用程序导航栏支持,请在您的代码中添加此扩展。
import UIKit
extension UIViewController {
open func showNavigationBar(_ large: Bool,
_ animated: Bool,
titleColor: UIColor,
barTintColor: UIColor,
fontSize: CGFloat) {
navigationController?.navigationBar.barTintColor = barTintColor
navigationController?.navigationBar.backgroundColor = barTintColor
navigationController?.navigationBar.isTranslucent = true
self.navigationController?.setNavigationBarHidden(false, animated: animated)
if large {
self.navigationController?.navigationBar.prefersLargeTitles = true
if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = barTintColor
appearance.titleTextAttributes = [.foregroundColor: titleColor]
appearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor,
NSAttributedString.Key.font: UIFont(resource: R.font.robotoMedium, size: fontSize)!]
navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.compactAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance = appearance
} else {
self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor,
NSAttributedString.Key.font: UIFont(resource: R.font.robotoMedium, size: fontSize)!]
}
} else {
self.navigationController?.navigationBar.prefersLargeTitles = false
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor,
NSAttributedString.Key.font: UIFont(resource: R.font.robotoMedium, size: 20.0)!]
}
}
}
然后简单的调用这个方法
self.showNavigationBar(true, true, titleColor: UIColor.blue, barTintColor: UIColor.red, fontSize: 32.0)
如果那么也不行,那么就用这个
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
search.searchBar.becomeFirstResponder()
}
另一种解决方案是在情节提要中添加一个高度为 0 的 UIView 和带有安全区域的机顶盒和带有 UIScrollView/UICollectionView/UITableVIew 或其他可滚动视图的底部,并删除 TopSafeArea 和 ScrollableView 顶部之间的直接约束。我知道这可能不是解决方案,但我在情节提要中做到了。