文本字段中的自动填充+建议

时间:2018-07-15 19:46:59

标签: ios swift uitextfield

我正在尝试在此处自动完成,然后按照我在互联网上找到的示例及其现在的方式进行操作,可以比较用户类型并显示建议,但是当用户按下Enter键时它完成了一封信。

我需要检测用户是否按了Enter键并完全填写了该词,因为这将触发一个触发器来自动填写我的表单上的某些字段。

代码如下:

class MyViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var textField: UITextField!
var autoCompletionPossibilities = ["Apple", "Pineapple", "Orange"]
var autoCompleteCharacterCount = 0
var timer = Timer()

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

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //1
    var subString = (textField.text!.capitalized as NSString).replacingCharacters(in: range, with: string) // 2
    subString = formatSubstring(subString: subString)
    if subString.count == 0 { // 3 when a user clears the textField
        resetValues()
    } else {
        searchAutocompleteEntriesWIthSubstring(substring: subString) //4
    }
    return true
}

func formatSubstring(subString: String) -> String {
    let formatted = String(subString.dropLast(autoCompleteCharacterCount)).lowercased().capitalized //5
    return formatted
}

func resetValues() {
    autoCompleteCharacterCount = 0
    textField.text = ""
}

func searchAutocompleteEntriesWIthSubstring(substring: String) {
    let userQuery = substring
    let suggestions = getAutocompleteSuggestions(userText: substring) //1

    if suggestions.count > 0 {
        timer = .scheduledTimer(withTimeInterval: 0.01, repeats: false, block: { (timer) in //2
            let autocompleteResult = self.formatAutocompleteResult(substring: substring, possibleMatches: suggestions) // 3
            self.putColourFormattedTextInTextField(autocompleteResult: autocompleteResult, userQuery : userQuery) //4
            self.moveCaretToEndOfUserQueryPosition(userQuery: userQuery) //5
        })
    } else {
        timer = .scheduledTimer(withTimeInterval: 0.01, repeats: false, block: { (timer) in //7
            self.textField.text = substring
        })
        autoCompleteCharacterCount = 0
    }
}

func getAutocompleteSuggestions(userText: String) -> [String]{
    var possibleMatches: [String] = []
    for item in autoCompletionPossibilities { //2
        let myString:NSString! = item as NSString
        let substringRange :NSRange! = myString.range(of: userText)

        if (substringRange.location == 0) {
            possibleMatches.append(item)
        }
    }
    return possibleMatches
}

func putColourFormattedTextInTextField(autocompleteResult: String, userQuery : String) {
    let colouredString: NSMutableAttributedString = NSMutableAttributedString(string: userQuery + autocompleteResult)
    colouredString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.lightGray, range: NSRange(location: userQuery.count,length:autocompleteResult.count))
    self.textField.attributedText = colouredString
}

func moveCaretToEndOfUserQueryPosition(userQuery : String) {
    if let newPosition = self.textField.position(from: self.textField.beginningOfDocument, offset: userQuery.count) {
        self.textField.selectedTextRange = self.textField.textRange(from: newPosition, to: newPosition)
    }
    let selectedRange: UITextRange? = textField.selectedTextRange
    textField.offset(from: textField.beginningOfDocument, to: (selectedRange?.start)!)
}

func formatAutocompleteResult(substring: String, possibleMatches: [String]) -> String {
    var autoCompleteResult = possibleMatches[0]
    autoCompleteResult.removeSubrange(autoCompleteResult.startIndex..<autoCompleteResult.index(autoCompleteResult.startIndex, offsetBy: substring.count))
    autoCompleteCharacterCount = autoCompleteResult.count
    return autoCompleteResult
}

}

0 个答案:

没有答案