ios - 高级自动完成 Swift

标签 ios swift uitableview uitextfield

我通过以下代码创建了一个简单的自动完成文本字段(其中自动完成选项显示在表格 View 中):

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()
    }


}

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

最佳答案

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

关于ios - 高级自动完成 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42941361/

相关文章:

iphone - AVCaptureVideoPreviewLayer镜像iPhone 4和iPad 2

ios - ARKit 和 Reality Composer - 如何使用图像坐标锚定场景

swift - UIButton 上的文本未更新 SWIFT

ios - 应用程序在发布版本中崩溃但在调试中不崩溃

ios - 如何保存在UITableView中滚动时消失的选中标记?

iphone - 从 webservices URL 获取密码并通过该密码访问

ios - 存储设置 ios5

swift - 让委托(delegate)在主线程以外的地方运行

ios - 在 didSelectRowAt indexPath 函数之外访问 IndexPath.row

ios - Swift:使用 UISearchController/Predicates 过滤结构数组