UISearchBarDelegate search button don't work swift 3 iOS 10.3

I had been looking for an answer and I hope you can help me. I don't see mistakes in the code but for some reason the UISearchBarDelegate just don't work when I press the "Search" button.

This is my class

class BusquedaViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!
var searchBar: UISearchBar!
var referencias: [Reference]!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
    searchBar.tintColor = UIColor.white
    searchBar.delegate = self
    self.parent?.navigationItem.titleView = searchBar
    referencias = DataManager.sharedInstance.obtenerReferencias()
}

override func viewWillAppear(_ animated: Bool) {
    self.parent?.title = "Busqueda"
}

//MARK: UISearchBar
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    var placa = searchBar.text
    if text.isEmpty {
        return true
    } else {
        let uper = text.uppercased()
        let allowed = "1234567890ABCDEFGHIJKLMNÑOPQRSTUVWXYZ-"
        if !allowed.contains(uper) || (placa?.characters.count)! > 9 {
            return false
        }
        searchBar.text = searchBar.text! + uper
        return false
    }
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchBar.showsCancelButton = true
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchBar.showsCancelButton = false
    searchBar.text = ""
    searchBar.endEditing(true)
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.endEditing(true)
}

//MARK: UITableView
func numberOfSections(in tableView: UITableView) -> Int {
    return referencias.isEmpty ? 1 : referencias.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    if referencias.isEmpty {
        //cell.textLabel?.text = NSLocalizedString("NO_REFERENCIAS", comment: "")
    } else {
        cell.textLabel?.text = referencias[indexPath.row].model
    }
    return cell
}
}

Upvotes: 1

Views: 1230

Answers (1)

Mark
Mark

Reputation: 7419

This is just a guess, but the shouldChangeTextIn range: method is returning false for the return key (character \n), and that could be affecting the other delegate method. Can you try modifying the method to use the below implementation, and see if the searchBarSearchButtonClicked method is called?

func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, 
               replacementText text: String) -> Bool {
    return true
}

Upvotes: 1

Related Questions