UISearchController - 搜索栏应该始终可见

UISearchController - search bar should be visible always

目标: 拥有一个始终可见的搜索栏。

  1. 视图控制器嵌入在导航控制器中
  2. 不存在 table 视图
  3. 当用户点击搜索栏时,搜索栏需要从其当前位置动画到导航栏顶部(向上),就像在 中一样iOS 联系人应用.
  4. 使用UISearchController

我做了什么:

  1. 我已将搜索栏添加到视图控制器的视图中
  2. 我手动呈现搜索视图控制器(下面的代码)

问题:

预期行为:

问题

  1. 我的方法正确吗?
  2. 如何设置动画并将搜索栏从当前位置向上移动?

代码:

    func setupSearchController() {
        searchController.searchResultsUpdater = self
        self.definesPresentationContext = false
        searchController.delegate = self
        searchController.hidesNavigationBarDuringPresentation = true

        let searchBar = searchController.searchBar

        view.addSubview(searchBar)

        searchBar.translatesAutoresizingMaskIntoConstraints = false

        searchBar.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
        searchBar.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
        searchBar.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor).active = true

    }

    func presentSearchController(searchController: UISearchController) {
        let searchBar = searchController.searchBar

        searchBar.removeFromSuperview()

        let baseView = searchController.view

        baseView.addSubview(searchBar)

        searchBar.leadingAnchor.constraintEqualToAnchor(baseView.leadingAnchor).active = true
        searchBar.trailingAnchor.constraintEqualToAnchor(baseView.trailingAnchor).active = true
        searchBar.topAnchor.constraintEqualToAnchor(searchController.topLayoutGuide.bottomAnchor).active = true

        self.presentViewController(searchController, animated: true) {

        }
    }

我不太理解你的逻辑,但我只能说你可以很容易地实现它。

解决方案

  • 在您的 Interface Builder 上创建一个 UIView 容器 searchControllersearchBar 并将约束设置为 以下:

  • UIView 连接到 UIViewController 并将其命名为 searchBarContainer
  • 创建您要使用的 属性 个 UISearchControllervar searchController: UISearchController! = nil
  • searchController.searchBar添加到searchBarContainer

幸运的是你的控制器应该是这样的:(请注意,我在这里没有实现委托,但你可以处理它,因为这与动画无关:))

class SearchViewController: UIViewController {
    var searchController: UISearchController! = nil
    @IBOutlet weak var searchBarContainer: UIView!

    // MARK: - View Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController = UISearchController(searchResultsController: nil)
        self.searchBarContainer.addSubview(searchController.searchBar)
    }

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

        // Setup the frame each time that the view appears in order to fit the width of the screen
        // If you use autolayout just call searchController.searchBar.layoutIfNeeded()
        var frame = searchController.searchBar.bounds
        frame.size.width = self.view.bounds.size.width
        searchController.searchBar.frame = frame
    }
}

输出

我的解决方案

iOS 联系人