Aggiunta barra di ricerca a livello di programmazione per tableview in swift

Ho un campo di testo che rappresenta una tableview come inputview. Vorrei aggiungere 2 cose per questo tableview.

1) aggiungere una barra di ricerca.
2) aggiungere cancell pulsante superiore della 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()
}
}

Il problema è che con questo codice, non di ricerca. Anche quando clicco la barra di ricerca è chiudere la tableview e mi riporta indietro al viewcontroller. Come posso risolvere questo problema?

e come posso aggiungere il pulsante annulla per questo tableview?

  • UISearchController Apple codice di esempio : Apple codice di esempio Questo vi aiuterà a realizzare.
  • Potrebbe aiutarmi se sapevo obiettivo c.. sembra molto complicato per me. Terrò esaminando il codice.
  • Il codice di esempio non è l’apertura di esecuzione correttamente con Xcode 10.
  • sì, la domanda 3 anni fa. Potrebbe essere il motivo.
InformationsquelleAutor Berk Kaya | 2016-07-21

 

4 Replies
  1. 14

    Questo aggiungerà un 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...
    }
  2. 2

    In swift 4.1 e Xcode 9.4.1

    Step1

    Aggiungere UISearchBarDelegate per il view controller.

    Step2

    //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

    Fase 3

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

    Ecco il codice snipet di swift per la stessa Per più basta consultare Apple Doc menzionato nel commento.

    UISearchDisplayController è sconsigliata a IOS8.0, e si consiglia di utilizzare UISearchController

    Spero che questo ti aiuterà molto

    ContactTVC

    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()
    
    }
    }

    ///La table view controller e responsabile della visualizzazione filtrata prodotti come l’utente digita nel campo di ricerca.

    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
    }
    }

    Grazie

  4. 1

    //prima di scrivere delegato per la ricerca “UISearchBarDelegate”
    //MARK:- pulsante di Ricerca azione

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

Lascia un commento