UISearchBarDelegate搜索按钮不工作swift 3 iOS 10.3
我一直在寻找答案,希望你能帮助我。我没有看到代码中有错误,但由于某种原因,当我按下搜索按钮时,UISearchBarDelegate无法工作 这是我的课UISearchBarDelegate搜索按钮不工作swift 3 iOS 10.3,ios,swift3,uisearchbardelegate,Ios,Swift3,Uisearchbardelegate,我一直在寻找答案,希望你能帮助我。我没有看到代码中有错误,但由于某种原因,当我按下搜索按钮时,UISearchBarDelegate无法工作 这是我的课 class BusquedaViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var searchBar:
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
}
}
这只是猜测,但是shouldChangeTextIn range:方法对返回键字符返回false\n,这可能会影响其他委托方法。能否尝试修改该方法以使用以下实现,并查看是否调用了searchBarSearchButtonClicked方法
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
return true
}
其他代理被调用或未被调用。您确定您是通过代码而不是故事板添加搜索栏吗?实际上,除了searchBarSearchButtonClickedNo问题外,一切都正常。如果答案对你有帮助的话,也可以随意投票。