iOS/코드조각

[iOS, Swift] 텍스트필드 AutoComplete 자동완성 기능

검은참깨두유vm 2022. 7. 13. 19:09
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

// AutoComplete String
var suggestionsArray: [String] = ["자동완성"]

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

 

extension ViewController: UITextFieldDelegate { // 자동완성
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return !autoCompleteText(in: textField, using: string, suggestionsArray: suggestionsArray)
    }
    
    func autoCompleteText(in textField: UITextField, using string: String, suggestionsArray: [String]) -> Bool {
        if !string.isEmpty,
            let selectedTextRange = textField.selectedTextRange,
            selectedTextRange.end == textField.endOfDocument,
            let prefixRange = textField.textRange(from: textField.beginningOfDocument, to: selectedTextRange.start),
            let text = textField.text(in: prefixRange)
        {
            let prefix = text + string
            let matches = suggestionsArray.filter {
                $0.hasPrefix(prefix)
            }
            if (matches.count > 0) {
                textField.text = matches[0]
                if let start = textField.position(from: textField.beginningOfDocument, offset: prefix.count) {
                    textField.selectedTextRange = textField.textRange(from: start, to: textField.endOfDocument)
                    return true
                }
            }
        }
        return false
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
}

 

 

반응형