UITextFiled 사용시 특정 키를 감지해서 별도로 로직을 처리해 줘야 되는 경우
Back Space : - 92
SPACE : -60
ENTER : - 83
,(콤마) : -48
# : -57
/*
UITextField 에서 tag 표시하는 로직 일부
예시] #망고 #사과 #바나나
문자열을 입력 후 Enter 또는 ,(콤마) 또는 Space 입력시 자동으로 #을 입력해 준다.
*/
// text가 변경할지에 대한 delegate 요청 메서드
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 입력된 문자 char 변환
if let char = string.cString(using: String.Encoding.utf8) {
// char -> Key Code로 변환 (-57 : #)
let tagInputKey = strcmp(char, "\\b\\,\\n")
print(">>>> CChar utf8 \(char) / \(tagInputKey)")
if textField.tag == TAGVIEW_TAG {
// '#' 입력 금지
if tagInputKey == -57 {
// 토스트 알림 처리 필요할듯.
return false
}
// Back Space (입력 삭제)
if tagInputKey == -92 {
tagCurrentString = String(tagCurrentString.dropLast(1))
return true
}
if tagInputKey == -82 || tagInputKey == -60 || tagInputKey == -48 {
setTagViewReload(split: ["#", " "])
return true
}
} else {
if tagInputKey == -82 {
textField.endEditing(true)
}
}
}
return true
}
/// 태그 문자열 재정렬 ( '#', '공백' 으로 구분)
func setTagViewReload(split: CharacterSet) {
tagStrings.removeAll()
let tags = tagCurrentString.components(separatedBy: split).map({ $0 }).filter({!$0.isEmpty})
if tags.count == 0 {
log(direction: .ETC, ofType: self, datas: "tag count zero!")
return
}
for newTag in tags {
tagStrings.append(String(newTag))
}
self.tagCurrentString = ""
self.tagTextField.text = ""
for tag in self.tagStrings {
self.tagTextField.text = self.tagTextField.text! + "#\(tag) "
}
// tag 정보 업데이트
log(direction: .ETC, ofType: self, datas: self.tagTextField.text)
}
// Text 추가 입력되면 호출 shouldChangeTextIn = true일경우 이후 호출됨
func textFieldDidChangeSelection(_ textField: UITextField) {
if textField.tag == TAGVIEW_TAG {
self.tagCurrentString = textField.text!
}
}
// 입력포커스 해제시
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == TAGVIEW_TAG {
setTagViewReload(split: ["#", " "])
textField.endEditing(true)
}
}
// 입력포커스 생성시
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.tag == TAGVIEW_TAG {
// 태그 입력 PlaceHolder 적용된 상태 초기화
if textField.textColor == UIColor.warmGrey {
textField.textColor = UIColor.white
textField.text = ""
}
}
}
'Swift > 문법' 카테고리의 다른 글
[SWIFT]Safe Array 사용하기 (0) | 2023.06.27 |
---|---|
[SWIFT]Json String 형식 Json -> String 파싱 (0) | 2023.06.27 |
[SWIFT]String 문자열 마지막 글자 삭제 (0) | 2023.06.27 |
[SWIFT]vDSP add 함수 사용하기 (0) | 2023.06.26 |
[SWIFT]UnsafeMutablePointer<AudioBufferList> to Int16 Array 변경 (0) | 2023.06.26 |