【问题标题】:How to add a UISearchbar on every view如何在每个视图上添加 UISearchbar
【发布时间】:2017-02-18 23:56:54
【问题描述】:

或者在所有需要的视图上手动实现搜索栏的简单方法是否正确? 我必须在我的应用程序的几乎每个视图上添加一个搜索栏(除了在每个视图导航栏上添加一个按钮)。但我不确定实现这一目标的最佳方法是什么。

  1. 我应该继承一个导航栏还是整个导航控制器?
  2. 或者在所有需要的视图上手动实现搜索栏的简单方法是否正确?

如果我应该继承哪个类是正确的? 我的想法是将UINavigationController 子类化,添加UISearchBar 并在获取搜索结果后打开带有搜索结果的UITableViewController

这是我目前的方法(没有实现搜索栏委托只是为了检查我是否在一个有效的解决方案上) ​

import UIKit

class MyNavigationControllerViewController: UINavigationController {

    var searchController : UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationBar.backgroundColor = UIColor.red
        self.createSearchBar()
    }

    func createSearchBar() {
        let searchBar = UISearchBar()
        searchBar.showsCancelButton = true
        searchBar.placeholder = "Search"
        // searchBar.delegate = self
        self.navigationItem.titleView = searchBar
    }
}

至少,调试器输入MyNavigationController,但搜索栏和红色导航栏都不可见。

【问题讨论】:

  • 我很抱歉,但由于我的 mac 上的剪贴板复制错误,在编辑您的问题时,我已经复制了句子。我指望编辑请求被拒绝,所以没有 edit cancel 功能。你能正确地重新构建问题吗?

标签: ios swift uinavigationcontroller


【解决方案1】:

我建议使用带有扩展的协议,该协议将提供导航栏和项目的配置。然后您可以扩展任何视图控制器以符合它并使用协议的默认实现。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        configureNavigationBar()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension ViewController: SearchController { }

protocol SearchController: class { }
extension SearchController where Self: UIViewController {

    func configureNavigationBar() {
        navigationController?.navigationBar.backgroundColor = UIColor.red
        let search = UISearchBar()
        search.placeholder = "Search"
        search.showsCancelButton = true
        navigationItem.titleView = search
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2020-04-30
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多