반응형
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
}
}
반응형
'iOS > 코드조각' 카테고리의 다른 글
[iOS, Swift] Swift Closure Snippet (0) | 2022.07.13 |
---|---|
[iOS, Swift] String to Data (Base64 Encoded String) (0) | 2022.07.13 |
[iOS, Swift] ScrollView 키보드 화면 처리하기 (0) | 2022.07.12 |
[iOS, Swift] ScrollView endEditing 사용하기 (0) | 2022.07.12 |
[iOS, Swift] Alamofire responseDecodable 사용하기 (0) | 2022.07.12 |