使用NSpredicate

时间:2017-04-10 07:23:36

标签: swift nspredicate searchbar

我正在为smartsearch制作应用。我已经通过将参数创建为字符串然后附加字符串来实现。然后,对于搜索,我实现了从搜索中搜索的过滤器。但它变得冗长。我想在紧凑型中使用NSPredicate。

我的代码在这里。任何人都可以使用NSPredicate和NSCompoundPredicate来制作它

import UIKit    
struct Request{    
var type:String!
var firstName:String!
var lastName:String!

var combineString:String {
    get {
        let text = "\(self.type!) \(self.firstName) \(self.lastName)"
        return text
    }
}
init() {
    self.type = ""
    self.firstName = ""
    self.lastName = ""
}
init(_ type:String,_ firstName:String,_ lastName:String) {
    self.type = type
    self.firstName = firstName
    self.lastName = lastName
}}

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

@IBOutlet var searchbar:UISearchBar!
@IBOutlet var headline:UILabel!
@IBOutlet var table:UITableView!

var type:Array = [String]()
var firstName:Array = [String]()
var lastName:Array = [String]()

var tempResults = Array<[Request]>()
var requestArray = Array<Request>()
var filteredArray = Array<Request>()
var isSearching = false

type = [“4343”, “45450”, “68468”, “4686”, “56461”, “48661”]
firstName = [“Tom”, “Michel”, “Steve”, “Rahul”, “Iswar”, “Kuldeep”]
lastName = [“Moody”, “Clark”, “Smith”, “Kumar”, “Pandey”, “Yadav”]


        for i in 0..<requestTypeArr.count {
            let type = self.type[i]
            let firstName = self.firstName[i]
            let lastName = self.lastName[i]

            var request = Request()
            request.type = type
            request.firstName = firstName
            request.lastName = lastName
            self.requestArray.append(request)
        }
        let string = String(format: "Total list No %ld", self.requestArray.count)

        self.headline.text = string
        self.table.delegate = self
        self.table.dataSource = self
        self.table.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
        self.table.estimatedRowHeight = 44
        self.table.rowHeight = UITableViewAutomaticDimension
        self.searchbar.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.isSearching == true {
        return self.filteredArray.count
    }
    return self.requestArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RquestDetailTableViewCell") as! RquestDetailTableViewCell
    var request = self.requestArray[indexPath.row]
    if self.isSearching == true {
        request = self.filteredArray[indexPath.row]
    }
    cell.type.text = request.type
    cell.firstName.text = request.firstName
    cell.lastName.text = request.lastName
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}}

extension ViewController : UISearchBarDelegate {
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    self.isSearching = true
   // self.table.reloadSections([0], with: .automatic)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    //Filter one
    //print("Search Query:- \(searchText)")
    if searchText.components(separatedBy: .whitespaces).joined(separator: "").characters.count == 0 {
        if self.isSearching == true {
            self.isSearching = false
            self.filteredArray = Array<Request>()
            self.tempResults = Array<[Request]>()
        }
    }else {
        if self.isSearching == false {
            self.isSearching = true
        }

        var temp = Array<Request>()
        if self.tempResults.count == 0 {
            temp = self.requestArray.filter({ (object) -> Bool in
                //print("\nSearch Text = \(searchText.lowercased()) \nand Source Combine String = \(object.combineString.lowercased())")
                let lowercaseInput = searchText.lowercased()
                let lowercaseSource = object.combineString.lowercased()
                let sourceComponents = lowercaseSource.components(separatedBy: .whitespaces)
                let inputComponents = lowercaseInput.components(separatedBy: .whitespaces)
                let sourceSet = Set(sourceComponents)

                var inputSet = Set(inputComponents)
                if let index = inputSet.index(of: ""){
                    _ = inputSet.remove(at: index)
                }
                var filtered = [String]()
                inputSet.forEach({ (word) in

                    let temp = sourceSet.filter({$0.contains(word)})
                    //let temp2 = sourceSet.filter({$0.hasPrefix(word)})
                    filtered.append(contentsOf: temp)

                   // let temp2 = sourceSet.filter({$0.hasPrefix(word)})
                    //filtered.append(contentsOf: temp2)
                })

                let set = Set(filtered)
                var isOK = set.isSubset(of: sourceSet)
                if set.count == 0 {
                    isOK = false
                }
                return isOK
            })
            self.filteredArray = temp
        }else {
            if let last = self.tempResults.last {
                temp = last.filter({ (object) -> Bool in
                    let lowercaseInput = searchText.lowercased()
                    let lowercaseSource = object.combineString.lowercased()
                    let lastInputWord = lowercaseInput.components(separatedBy: .whitespaces).last!

                    let sourceComponents = lowercaseSource.components(separatedBy: .whitespaces)
                    let inputComponents = [lastInputWord]
                    let sourceSet = Set(sourceComponents)

                    let inputSet = Set(inputComponents)
                    var filtered = [String]()
                    inputSet.forEach({ (word) in
                        let temp = sourceSet.filter({$0.contains(word)})
                        //let temp2 = sourceSet.filter({$0.hasPrefix(word)})
                        filtered.append(contentsOf: temp)
                    })

                    let set = Set(filtered)
                    var isOK = set.isSubset(of: sourceSet)
                    if set.count == 0 {
                        isOK = false
                    }
                    return isOK
                })
                self.filteredArray = temp
            }
        }

    }
    self.table.reloadSections([0], with: .automatic)
}
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " " {
        self.tempResults.append(self.filteredArray)
    }
    if range.length == 1 {
        //Handle Backspace/delete
        let string = searchBar.text! as NSString
        let temp = string.substring(with: range) as String
        let newRange = string.range(of: temp, options: .backwards)
        let newText = string.replacingCharacters(in: newRange, with: "")
        let words = newText.components(separatedBy: .whitespaces).count
        if words > 1 {
            print("word count = \(words)")
            let count = self.tempResults.count
            if count > words {
                self.tempResults.removeLast()
            }
        }else {
            self.tempResults = Array<[Request]>()
        }
    }
    return true
}
}

0 个答案:

没有答案