우선 UITextFieldDelegate 원하는 caracters를 입력 할 수 있도록 허용 여부와 특정 방법이있다 : func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
. 즉
, 당신이 제어 할 수있는이 방법을 구현하여 사용자가 문자, 숫자로 입력 할 수있는 ... 여기 내가 몇 가지 예제와 함께 만든 방법입니다 : 다음
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let candidate = (text as NSString).replacingCharacters(in: range, with: string)
switch textField.tag {
//Restrict to only have 2 number digits and max 23 for hours for UITextfields having tags 1, 3, 5 and 7
case 1, 3, 5, 7:
return textField.hasHourPattern(in: candidate, range: NSRange(location: 0, length: candidate.characters.count))
//Restrict to only have 2 number digits and max 59 for minutes fr UITextFields having tags with 2, 4, 6 and 8
case 2, 4, 6, 8:
return textField.hasMinutePattern(in: candidate, range: NSRange(location: 0, length: candidate.characters.count))
//Restrict to have 3 digits max for interger part then . and 2 digits for decimal part for UITextField having tag 9
case 9:
return textField.hasTauxPattern(in: candidate, range: NSRange(location: 0, length: candidate.characters.count))
default:
return true
}
}
, 나는 UITextField에 확장 클래스를 사용하여 입력 표현식을 점검하는 3 가지 함수를 만들려면 정규 표현식. 내가 입력 한 표현이 특정 패턴과 일치하는 경우 제어 :
extension UITextField {
// Patterns function
// If has hour pattern : 0 to 23 include
func hasHourPattern(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Bool {
let regex = try? NSRegularExpression(pattern: "^(?:[0-9]|0[0-9]|1[0-9]|2[0-3]|)$", options: [])
return regex?.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) != nil
}
// If has minute pattern : 0 to 59 include
func hasMinutePattern(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Bool {
let regex = try? NSRegularExpression(pattern: "^(?:[0-9]|0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|)$", options: [])
return regex?.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) != nil
}
// If has taux pattern : 3 decimals . and 2 decimals
func hasTauxPattern(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Bool {
let regex = try? NSRegularExpression(pattern: "^\\d{0,3}(\\.\\d{0,2})?$", options: [])
return regex?.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) != nil
}
...//Create whatever function to check a pattern you want
}
또한, 당신은 또한 UITextField에 속성을 keyboardType
당신이 필요로하는 키보드 유형을 표시하여 원하는 문자의 유형을 나타냅니다이라고 할 수 있습니다.
"UItextfield로 상점 등록 정보를 정의 할 수 없습니다." –
확장 기능에 저장된 등록 정보를 추가 할 수 없습니다. 이 경우 하위 클래스를 만드는 것이 가장 간단한 방법처럼 보입니다. – Losiowaty
UITextField 유형의 사용자 정의 클래스를 만들고 원하는 속성을 정의하십시오. 그런 다음 UITextFieldDelegate를 사용하여 사용자 정의 클래스를 확장하고 원하는 곳 어디에서나 사용할 수 있습니다. –