【问题标题】:Case Insensitive (Not Case Sensitive) Search with Swift 2使用 Swift 2 进行不区分大小写(不区分大小写)搜索
【发布时间】:2016-01-03 04:04:03
【问题描述】:

我在 Parse 中有一门名为“Friends”的课程。我添加了一个搜索栏(没有搜索显示控制器)。我希望能够通过搜索“john doe”来搜索“John Doe”。我能够做到这一点的唯一方法是在 Parse 中将 "first_name""last_name" 下的“朋友”全部设为小写。然后我将我的 searchBar.text 转换为 lowerCaseString 并且它可以工作。我似乎无法将"first_name""last_name" 转换为lowerCaseString
有任何想法吗?谢谢!


class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var mySearchBar: UISearchBar!


var searchResults = [String]()

override func viewDidLoad() {
    super.viewDidLoad()



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
    searchBar.resignFirstResponder()
    print("Search word = \(searchBar.text!)")


    let firstNameQuery = PFQuery(className:"Friends")
    firstNameQuery.whereKey("first_name".lowercaseString, matchesRegex: searchBar.text!.lowercaseString)



    let lastNameQuery = PFQuery(className:"Friends")
    lastNameQuery.whereKey("last_name".lowercaseString, matchesRegex: searchBar.text!.lowercaseString)

    // lastNameQuery.whereKey("last_name", matchesRegex: "(?i)\(searchBar.text)") <- Instead of firstNameQuery.whereKey("first_name", containsString: searchBar.text)






    let query = PFQuery.orQueryWithSubqueries([firstNameQuery, lastNameQuery])

    query.findObjectsInBackgroundWithBlock {
        (results: [AnyObject]?, error: NSError?) -> Void in

        if error != nil {
            let myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle:UIAlertControllerStyle.Alert)

            let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)

            myAlert.addAction(okAction)

            self.presentViewController(myAlert, animated: true, completion: nil)

            return
        }

        if let objects = results as? [PFObject] {

            self.searchResults.removeAll(keepCapacity: false)

            for object in objects {
                let firstName = object.objectForKey("first_name") as! String
                let lastName = object.objectForKey("last_name") as! String
                let fullName = firstName + " " + lastName

                self.searchResults.append(fullName)
            }

            dispatch_async(dispatch_get_main_queue()) {
                self.myTableView.reloadData()
                self.mySearchBar.resignFirstResponder()

            }



        }




    }

}




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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) 

    myCell.textLabel?.text = searchResults[indexPath.row]

    return myCell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    mySearchBar.resignFirstResponder()
}

func searchBarCancelButtonClicked(searchBar: UISearchBar)
{
    mySearchBar.resignFirstResponder()
    mySearchBar.text = ""
}

@IBAction func refreshButtonTapped(sender: AnyObject) {
    mySearchBar.resignFirstResponder()
    mySearchBar.text = ""
    self.searchResults.removeAll(keepCapacity: false)
    self.myTableView.reloadData()
}


}

【问题讨论】:

  • 可能尝试将搜索(第一个字母)小写和大写,以便匹配任何单个单词。

标签: swift parse-platform


【解决方案1】:

使用 NSStringCompareOption 进行不区分大小写的搜索。如果您使用此函数,则结果将显示包含子字符串的所有字符串。

let range = temp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
if range.location != NSNotFound {
    print("match")
}

如果您只想要以特定搜索字符串开头的结果。只需检查范围是否从字符串的第一个字符开始。

【讨论】:

  • 仍然不确定如何在我的代码中实现它。
【解决方案2】:

将两个文本都转换为小写(搜索文本和数组字符串)

   let text = searchText.lowercased()
        filtered = data.filter({

            let t = $0.dr_name.lowercased().contains(text)
           
            if t{
                return true
            }else{
                 return false
            }
           
            
        })

【讨论】:

  • 这看起来很复杂,为什么不直接返回$0.dr_name.lowercased().contains(text),因为那将是一个布尔值
猜你喜欢
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 2012-12-20
  • 2010-09-12
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
相关资源
最近更新 更多