2017-03-22 38 views
0

我創建了一個簡單的自動完成文本框(其中自動完成選項都顯示在一個tableview中)通過下面的代碼:先進的自動完成斯威夫特

import UIKit 

class SchoolViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { 

    @IBOutlet weak var schoolTextField: UITextField! 
    @IBOutlet weak var autoCompleteTableView: UITableView! 

    let schoolPossibilities = ["Redwood", "Fisher", "Bellermen", "Saratoga", "Los Gatos", "Cambell", "Mooreland", "Harker", "Challenger", "Saint Andrews", "Beckens", "Lynbrook", "Menlo", "Gunn", "Aragon", "Kipp"] 
    var autoCompleteSchools = [String]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     autoCompleteTableView.delegate = self 
     schoolTextField.delegate = self 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "someCell", for: indexPath) 
     cell.textLabel?.text = autoCompleteSchools[indexPath.row] 
     return cell 
    } 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return autoCompleteSchools.count 
    } 

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     if let text = schoolTextField.text{ 
      let substring = (text as NSString).replacingCharacters(in: range, with: string) 
      searchAutoCompleteEntries(withSubstring: substring) 
     } 
     return true 
    } 

    func searchAutoCompleteEntries(withSubstring substring: String){ 
     autoCompleteSchools.removeAll() 
     for key in schoolPossibilities{ 
      let string = key as NSString 
      let range = string.range(of: substring) 
      if range.location == 0{ 
       autoCompleteSchools.append(key) 
      } 
     } 
     autoCompleteTableView.reloadData() 
    } 


} 

的問題是,選擇只顯示了,如果什麼東西被輸入在文本字段中是一個精確匹配。如何更改此代碼,以便它可以容忍大寫字母和小寫字母以及輕微的變化?

+0

選項傳遞相應的選項給'(作者:)範圍'調用。請參閱文檔。 – rmaddy

回答

1

使用NSCaseInsensitiveSearch作爲比較

outputString.rangeOfString(String, options: NSStringCompareOptions, range: <#T##Range<Index>?#>, locale: <#T##NSLocale?#>) 
+0

什麼是outputString引用? –

+0

「outputString」是您想要執行檢查的字符串。在你的情況下,它是「字符串」(讓string = key作爲NSString) – Joe