UISearchbar using UItextfield in swift 4

2019-07-31 02:01发布

问题:

I am working on JSON. My Json data print into the tableview. I want to filtered that data with searchbar. So I put Textfield for using the Searchbar. I use reference from this website

http://findnerd.com/list/view/How-to-create-your-own-search-bar-in-Swift-Not-using-UISearchBar/20577/

My Search bar is working but not properly. I want to filter data after I write 3 Words in searchbar.If I write "Ku" then my tableview remain hide. If I write "kus" in searchbar then searchbar started searching and show me filtered data in tableview started from "kus". my searchbar related code are these

struct PatientData:Decodable {
var ID : String
var dt_bod : String
var e_gender : String
var int_glcode : String
var var_email : String
var var_fname : String
var var_phoneno : String
var var_uname : String

init(userdata : [String:Any]) {
    self.ID = userdata["ID"] as! String
    self.dt_bod = userdata["dt_bod"] as! String
    self.e_gender = userdata["e_gender"] as! String
    self.int_glcode = userdata["int_glcode"] as! String
    self.var_email = userdata["var_email"] as! String
    self.var_fname = userdata["var_fname"] as! String
    self.var_phoneno = userdata["var_phoneno"] as! String
    self.var_uname = userdata["var_uname"] as! String

} 

var tabledata = [String]()
var tableFilterData = [String]()
var patientDetails = [PatientData]()

@IBAction func textfieldchanged(_ sender: Any) {
    tableview.isHidden = true
}

my textfield change character function

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{

    let searchText  = textField.text! + string
    if searchText.count >= 3 {
        tableview.isHidden = false

        tableFilterData = tabledata.filter({ (result) -> Bool in
            return result.range(of: searchText, options: .caseInsensitive) != nil
        })

        print(tableFilterData)   // I got filtered data here but how to show this data into the tableview
        tableview.reloadData()
    }
    else{
        tableFilterData = []
    }
    return true
}

tableview part is

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return patientDetails.count
     }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell!

    let aa = patientDetails[indexPath.row].var_fname + " , " + patientDetails[indexPath.row].dt_bod + " , " + patientDetails[indexPath.row].var_phoneno

    self.tabledata.append(aa)

        cell.textLabel?.text = aa
        cell.textLabel?.font = searchTextfield.font

    return cell
}

回答1:

Try this:

@objc func textFieldActive() {
    tableView.isHidden = tableFilterData.count > 0 ? false : true
}

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{

    let searchText  = textField.text! + string

    if searchText.count >= 3 {
        tableView.isHidden = false

        tableFilterData = tabledata.filter({ (result) -> Bool in
            return result.range(of: searchText, options: .caseInsensitive) != nil
        })

        tableView.reloadData()
    }
    else{
        tableFilterData = []
    }

    return true
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let data = tableFilterData[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = data

    return cell
}


回答2:

You can check size of text before filter:

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{

    var searchText  = textField.text! + string

    if string  == "" {
        searchText = (searchText as String).substring(to: searchText.index(before: searchText.endIndex))
    }
    if searchText == "" {
        isSearch = false
        tableview.reloadData()
    }
    else{
        if searchText.count > 2 {
           getSearchArrayContains(searchText)
        }  
    }
    return true
}


回答3:

Please use this code:-

func getSearchArrayContains(_ text : String) {

    tableFilterData = tableData.filter({$0.lowercased().contains(text)})
    isSearch = true
     tableview.reloadData()
}

For should three character use this linkenter link description here:-

Thanks