【问题标题】:UISearchBarDelegate search button don't work swift 3 iOS 10.3UISearchBarDelegate 搜索按钮不起作用 swift 3 iOS 10.3
【发布时间】:2017-08-29 03:12:40
【问题描述】:

我一直在寻找答案,希望您能帮助我。我没有在代码中看到错误,但由于某种原因,当我按下“搜索”按钮时 UISearchBarDelegate 不起作用。

这是我的课

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

【问题讨论】:

  • 其他代表是否被调用
  • 您确定要通过代码而不是 Storyboard 来添加搜索栏吗?
  • 实际上一切正常,除了“searchBarSearchButtonClicked”

标签: ios swift3 uisearchbardelegate


【解决方案1】:

这只是一个猜测,但 shouldChangeTextIn range: 方法的返回键(字符 \n)返回 false,这可能会影响其他委托方法。能否尝试修改方法使用下面的实现,看看是否调用了searchBarSearchButtonClicked方法?

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

【讨论】:

  • 没问题。如果对您有帮助,也请随意对答案进行投票。
猜你喜欢
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多