【问题标题】:Advanced Auto Complete Swift高级自动完成 Swift
【发布时间】:2017-03-22 01:55:32
【问题描述】:

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

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


}

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

【问题讨论】:

  • 将适当的选项传递给range(of:) 调用。请参阅文档。

标签: ios swift uitableview uitextfield


【解决方案1】:

使用 NSCaseInsensitiveSearch 作为比较选项

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

【讨论】:

  • outputString 指的是什么?
  • "outputString" 是您要在其中执行检查的字符串。在您的情况下,它是“字符串”(让 string = key as NSString)
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2015-03-23
  • 2015-03-20
  • 2015-10-10
  • 1970-01-01
  • 2020-01-05
相关资源
最近更新 更多