iOS/코드조각

[iOS, Swift] UITextField 특정 글자 제한하기

검은참깨두유vm 2022. 8. 21. 18:26
반응형

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

 

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    let allowedCharacters = CharacterSet(charactersIn: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuxyz").inverted
    
    let components = string.components(separatedBy: allowedCharacters)
    let filtered = components.joined(separator: "")
    
    if string == filtered {
        return true
    } else {
        return false
    }
    
}

 

allowedCharacters 외의 글자는 입력이 불가능하다.

반응형