高级自动完成Swift

时间:2017-03-22 01:55:33

标签: ios swift uitableview uitextfield

我通过以下代码创建了一个简单的自动填充文本字段(其中自动填充选项显示在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()
    }


}

问题是,只有在文本字段中键入的内容是完全匹配时才会显示选项。如何更改此代码,以便它可以容忍大写和小写字母以及轻微变化?

1 个答案:

答案 0 :(得分:1)

使用NSCaseInsensitiveSearch作为

中的比较选项
outputString.rangeOfString(String, options: NSStringCompareOptions, range: <#T##Range<Index>?#>, locale: <#T##NSLocale?#>)