ios 以编程方式将搜索栏快速添加到 tableview

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38508720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:44:59  来源:igfitidea点击:

Adding search bar programmatically to tableview in swift

iosswiftuitableviewuisearchbar

提问by Berk Kaya

I have an textfield which represents an tableview as its inputview. I want to add 2 things to this tableview.

我有一个文本字段,它代表一个 tableview 作为它的 inputview。我想在这个 tableview 中添加两件事。

1) add a search bar.
2) add cancell button to top of tableview.

1)添加搜索栏。
2)将取消按钮添加到tableview的顶部。

class enterYourDealVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating {
var tableView: UITableView  =   UITableView()
let searchController = UISearchController(searchResultsController: nil)

var dealAirports = [
    airPorts(name: "Airport1", shortcut: "AP1")!),
    airPorts(name: "Airport2", shortcut: "AP2")!)
]
var filteredAirports = [airPorts]()


//view did load
    tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
    tableView.delegate      =   self
    tableView.dataSource    =   self
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar
    toTextField.inputView = self.tableView

//here is my search function
func filterContentForSearchText(searchText: String, scope: String = "All") {
    filteredAirports = dealAirports.filter { ap in
        return ap.name.lowercaseString.containsString(searchText.lowercaseString)
    }

    tableView.reloadData()
}
}

The problem is with this code, it doesn't search. Also when I click the search bar it dismiss the tableview and returns me back to viewcontroller. How can I fix this?

问题在于这段代码,它不搜索。此外,当我单击搜索栏时,它会关闭 tableview 并将我返回到 viewcontroller。我怎样才能解决这个问题?

and how can I add cancel button to this tableview?

以及如何向此 tableview 添加取消按钮?

回答by Marco Castano

This will add a SeachBar

这将添加一个 SeachBar

lazy var searchBar:UISearchBar = UISearchBar()

override func viewDidLoad()
{
    searchBar.searchBarStyle = UISearchBarStyle.Prominent
    searchBar.placeholder = " Search..."
    searchBar.sizeToFit()
    searchBar.translucent = false
    searchBar.backgroundImage = UIImage()
    searchBar.delegate = self
    navigationItem.titleView = searchBar

}

func searchBar(searchBar: UISearchBar, textDidChange textSearched: String)
{
    ...your code...
}

回答by iOS

In swift 4.1 and Xcode 9.4.1

在 swift 4.1 和 Xcode 9.4.1 中

Step1

第1步

Add UISearchBarDelegate to your view controller.

将 UISearchBarDelegate 添加到您的视图控制器。

Step2

第2步

//Write this code in viewDidLoad() or your required function
let searchBar:UISearchBar = UISearchBar()
//IF you want frame replace first line and comment "searchBar.sizeToFit()"
//let searchBar:UISearchBar = UISearchBar(frame: CGRect(x: 10, y: 10, width: headerView.frame.width-20, height: headerView.frame.height-20))
searchBar.searchBarStyle = UISearchBarStyle.prominent
searchBar.placeholder = " Search..."
searchBar.sizeToFit()
searchBar.isTranslucent = false
searchBar.backgroundImage = UIImage()
searchBar.delegate = self
yourViewName.addSubview(searchBar)//Here change your view name

Step3

Step3

func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String) {
    //your code here....
}

回答by Chandan

Here is code snipet in swift for the same For more just refer Apple Doc mentioned in comment.

这是 swift 中相同的代码片段。更多信息请参考评论中提到的 Apple Doc。

UISearchDisplayController is deprecated in IOS8.0, and recommended to use UISearchController

UISearchDisplayController 在 IOS8.0 中被弃用,推荐使用 UISearchController

Hope this will help you alot

希望这会对你有很大帮助

ContactTVC

联系TVC

class ContactTVC:UITableViewController{   
// MARK: Types
/// State restoration values.
enum RestorationKeys : String {
    case viewControllerTitle
    case searchControllerIsActive
    case searchBarText
    case searchBarIsFirstResponder
}

struct SearchControllerRestorableState {
    var wasActive = false
    var wasFirstResponder = false
}


/*
 The following 2 properties are set in viewDidLoad(),
 They an implicitly unwrapped optional because they are used in many other places throughout this view controller
 */

/// Search controller to help us with filtering.
var searchController: UISearchController!

/// Secondary search results table view.
var resultsTableController: ResultsTableController!

/// Restoration state for UISearchController
var restoredState = SearchControllerRestorableState()
var arrayContacts: Array<CNContact> = []
var searchResultArrayContacts: Array<CNContact> = []

override func viewDidLoad() {
    super.viewDidLoad()

    resultsTableController = ResultsTableController()
// We want to be the delegate for our filtered table so didSelectRowAtIndexPath(_:) is called for both tables.
    resultsTableController.tableView.delegate = self

    searchController = UISearchController(searchResultsController: resultsTableController)

    searchController.searchResultsUpdater = self
    searchController.searchBar.sizeToFit()
    tableView.tableHeaderView = searchController.searchBar

    searchController.delegate = self
    searchController.dimsBackgroundDuringPresentation = false // default is YES
    searchController.searchBar.delegate = self    // so we can monitor text changes + others

  /*
     Search is now just presenting a view controller. As such, normal view controller
     presentation semantics apply. Namely that presentation will walk up the view controller
     hierarchy until it finds the root view controller or one that defines a presentation context.
     */

    definesPresentationContext = true

}

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

    // Restore the searchController's active state.
    if restoredState.wasActive {
        searchController.active = restoredState.wasActive
        restoredState.wasActive = false

        if restoredState.wasFirstResponder {
            searchController.searchBar.becomeFirstResponder()
            restoredState.wasFirstResponder = false
        }
    }
}

//MARK override TableViewDelegates/Datasource methods  
}
extension ContactTVC: UISearchResultsUpdating{

// MARK: UISearchResultsUpdating

func updateSearchResultsForSearchController(searchController: UISearchController) {

        if let text = searchController.searchBar.text where (text.isEmpty == false){
        {

                            // Hand over the filtered results to our search results table.

                            let resultsController = searchController.searchResultsController as! ResultsTableController

                            resultsController.filteredProducts = Array(searchResult)

                            resultsController.tableView.reloadData()

                        dispatch_async(dispatch_get_main_queue(), {
                            self.tableViewContacts.reloadData()
                        })

                }   
         }
}
}
//MARK: SearchBarDelegate
extension ContactTVC: UISearchBarDelegate{

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    if let text = searchBar.text where (text.isEmpty == false) {

          // update the search result array by filtering….


                if searchResult.count > 0{

                    self.searchResultArrayContacts = Array(searchResult)
                }
                else{

                    self.searchResultArrayContacts = Array(self.arrayContacts)
                }

                dispatch_async(dispatch_get_main_queue(), {
                    self.tableViewContacts.reloadData()
                })
     }
}


func searchBarCancelButtonClicked(searchBar: UISearchBar) {

    searchBar.text = nil
    searchBar.resignFirstResponder()

}
}

/// The table view controller responsible for displaying the filtered products as the user types in the search field.

/// 表视图控制器负责在用户在搜索字段中键入时显示过滤的产品。

class ResultsTableController: UITableViewController {
// MARK: Properties

let reusableIdentifier = "contactCell"

var filteredProducts = [CNContact]()

override func viewDidLoad() {

    self.tableView.emptyDataSetSource = self
    self.tableView.emptyDataSetDelegate = self

}


// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return filteredProducts.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell =  UITableViewCell(style: .Subtitle, reuseIdentifier: reusableIdentifier)

     var contact = CNContact()
     contact = filteredProducts[indexPath.row]

    // Configure the cell...
    cell.textLabel?.text = contact.givenName

    let phones = contact.phoneNumbers[0].value as! CNPhoneNumber

    cell.detailTextLabel?.text = phones.stringValue

    return cell
}
}

Thanks

谢谢

回答by Sai kumar Reddy

//first write delegate for search "UISearchBarDelegate" //MARK:- Search button action

//首先为搜索“UISearchBarDelegate”编写委托 //MARK:- 搜索按钮动作

@IBAction func searchWithAddress(_ sender: Any) {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.delegate = self
self.present(searchController, animated: true, completion: nil)
}