How to search local array in swift


Delegate :- UITextFiledDelegate, UITableViewDelegate, UITableViewDataSource

Let’s create one TableView Object

    @IBOutlet weak var tblObj: UITableView!

let’s create two array

    var arrayMain : NSArray = [ [“ItemName”:”abc” , “id”:”1” , ”price”:12] , [“ItemName”:”def” , “id”:”2” , ”price”:15], [“ItemName”:”ghi” , “id”:”3” , ”price”:52] ]

    var arraySearch : NSArray = NSArray()

Now let’s create one Bool variable
    var isSearch : Bool = false

TextFiled Delegate Method
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == txtSearch {
            
            var strSearch = ""
            strSearch = String(format: "%@%@", textField.text! , string)
            
            if string == "" {
                strSearch = (strSearch as NSString).substring(to: (strSearch.count) - 1)
            }
            let searchKey = “ItemName” // write here key for search you can write here any key like :- id, price.
            if strSearch.count > 0 {
                let predicateSearch = NSPredicate(format: "\(searchKey) CONTAINS[C] '\(strSearch)'")
                arraySearch = NSMutableArray(array: arrayMain.filtered(using: predicateSearch) as NSArray)
                isSearch = true
                self.tblObj.reloadData()
                
            } else {
                isSearch = false
                self.tblObj.reloadData()
            }
        }
        return true
    }


I Hop you Enjoy this tutorial keep touch in this blog for more update 

Comments

Popular posts from this blog

Windows Keys

how to send invite and give a access of selected application on App Store

how to display popover in TableView cell in swift