searchBar in tableView enquiries (Swift)

时间:2017-12-18 06:15:52

标签: ios swift xcode uitableview

I don't really know how to explain thats why I'm putting this title. But i do hope you can understand. As of right now, my searchBar is able to return results BUT i have to enter the entire name (For example: I have to type "EcoBooth" in order for the searchBar to return EcoBooth results.). How can i make it as though if i just enter "Eco", it will return EcoBooth based on just a few strings i type?

P.S: Do look at the 2 images attached for more info.

My TableView Controller codes

import UIKit import FirebaseDatabase

var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
var postData2 = [String]()
var currentpostDataArray = [String]()
var tableDataArray = [tableData]()
var searchArray = [tableData]()
var inSearchMode = false

class TableViewController: UITableViewController, UISearchBarDelegate {


    @IBOutlet var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpSearchBar()


        ref = Database.database().reference() //set the firebase reference

        // Retrieve the post and listen for changes
        databaseHandle = ref?.child("Posts2").observe(.value, with: { (snapshot) in
            // Code to execute when a child is added under "Posts"
            postData.removeAll()
            postData2.removeAll()
            tableDataArray.removeAll()

            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                let value = String(describing: snap.value!)
                let rating = (value as NSString).integerValue   

                postData.append(key)
                postData2.append(value)

                tableDataArray.append(tableData(boothName: key, boothRating: rating))
                currentpostDataArray = postData
            }

            self.tableView.reloadData()


        })

    }


    private func setUpSearchBar() {
        searchBar.delegate = self
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return currentpostDataArray.count
    }


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

        cell.textLabel?.text = currentpostDataArray[indexPath.row]
        cell.detailTextLabel?.text = postData2[indexPath.row] + " ♥"
        cell.detailTextLabel?.textColor = UIColor.red;
        return cell
    }




    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchArray.removeAll()
        searchArray = tableDataArray
        currentpostDataArray.removeAll()
        postData2.removeAll()
        if !searchText.isEmpty {
           for data in searchArray {
            let item = data.boothName
            if (searchText.lowercased().range(of: item) != nil) || data.boothName.lowercased() == searchText.lowercased() ||                 searchText.lowercased().contains(data.boothName.lowercased())
               {
                    currentpostDataArray.append(data.boothName)
                    let value = String(describing: data.boothRating)
                    postData2.append(value)
                }
            }
        }
        if searchText.isEmpty {
            loadDara()
        }
        self.tableView.reloadData()
    }



    func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        switch selectedScope {
        case 0:
            currentpostDataArray.removeAll()
            postData2.removeAll()
            for data in tableDataArray {
                currentpostDataArray.append(data.boothName)

                let value = String(describing: data.boothRating)
                postData2.append(value)
            }
            self.tableView.reloadData()

        case 1:
            currentpostDataArray.removeAll()
            postData2.removeAll()
            let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
            for data in sortedTableData {
                currentpostDataArray.append(data.boothName)

                let value = String(describing: data.boothRating)
                postData2.append(value)
            }
            self.tableView.reloadData()

        default:
            break

        }
        tableView.reloadData()
    }

    func loadDara() {
        for data in tableDataArray {
            currentpostDataArray.append(data.boothName)

            let value = String(describing: data.boothRating)
            postData2.append(value)
        }

    }

}

class tableData {
    var boothName: String
    var boothRating: Int
    init(boothName: String, boothRating: Int) {
        self.boothName = boothName
        self.boothRating = boothRating
    }
}

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

Replace

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchArray.removeAll()
    searchArray = tableDataArray
    currentpostDataArray.removeAll()
    postData2.removeAll()
    if !searchText.isEmpty {
       for data in searchArray {
        let item = data.boothName
        if (searchText.lowercased().range(of: item) != nil) || data.boothName.lowercased() == searchText.lowercased() ||                 searchText.lowercased().contains(data.boothName.lowercased())
           {
                currentpostDataArray.append(data.boothName)
                let value = String(describing: data.boothRating)
                postData2.append(value)
            }
        }
    }
    if searchText.isEmpty {
        loadDara()
    }
    self.tableView.reloadData()
}

With

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchArray.removeAll()
    searchArray = tableDataArray
    currentpostDataArray.removeAll()
    postData2.removeAll()
    if !searchText.isEmpty {
       for data in searchArray {
        let item = data.boothName
        if (item.lowercased().range(of: searchText.lowercased()) != nil)
           {
                currentpostDataArray.append(data.boothName)
                let value = String(describing: data.boothRating)
                postData2.append(value)
            }
        }
    }
    if searchText.isEmpty {
        loadDara()
    }
    self.tableView.reloadData()
}

答案 1 :(得分:0)

Use NSPredicate to search from array like this:

let searchPredicate = NSPredicate(format: "boothName CONTAINS[C] %@", searchText)

resultArr = (filteredArray as NSArray).filtered(using: searchPredicate)

You can prefer this link for more info about NSPredicate and also a swift code example : http://nshipster.com/nspredicate/