搜索功能逻辑无法正常工作

拉吉

这是我的单行搜索功能代码,无法正确过滤结果。谁能让我知道在代码中需要更改什么才能显示要搜索的文本前三个字符的数组元素。

对于我输入的第一个字符,它显示结果。但是输入第二和第三个元素不会显示任何结果

搜索功能逻辑:

searchFruit = data.filter{$0.range(of: textSearched, options: [.caseInsensitive, .anchored]) != nil}
Santosh Kumar JM

尝试这个:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var data = ["apple","bananna","dragon fruit", "mango","pineapple"]
var searchFruit = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tableView.delegate = self
    tableView.dataSource = self
    searchBar.delegate = self
    searchFruit = data
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return searchFruit.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    cell?.textLabel?.text = searchFruit[indexPath.row]
    return cell!
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchFruit = (searchText.isEmpty) ? self.data : self.data.filter({ (searchValue) -> Bool in
        return searchValue.range(of: searchText, options: .caseInsensitive) != nil
    })
    tableView.reloadData()

}

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章