2017-10-27 4 views
0

사용자가 특수 문자를 입력하지 못하도록 제한하기 위해 UITextField 확장을 사용하려고합니다. 아래 코드를 사용했지만 UItextfield가 저장소 특성을 정의 할 수 없습니다. 특수 charecter 집합을 정의 할 위치를 모르겠습니다.사용자가 특수 문자를 입력하는 것을 제한하기 위해 texfield 확장을 사용하는 방법?

extension UITextField:UITextFieldDelegate { 


    var allowSpecialCharecters:Bool { 
     get { 
      return self.allowSpecialCharecters 
     } 
     set { 
      self.allowSpecialCharecters = newValue 
     } 
    } 



    public func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool { 


     if !allowSpecialCharecters { 

      let set = NSCharacterSet(charactersIn: notAllowedCharacters); 
      let inverted = set.inverted; 

      let filtered = text.components(separatedBy: inverted).joined(separator: "") 
      print("String Filtered: \(filtered)") 
      return filtered != text; 

     } else { 
      return true 
     } 

    } 
} 
+0

"UItextfield로 상점 등록 정보를 정의 할 수 없습니다." –

+1

확장 기능에 저장된 등록 정보를 추가 할 수 없습니다. 이 경우 하위 클래스를 만드는 것이 가장 간단한 방법처럼 보입니다. – Losiowaty

+0

UITextField 유형의 사용자 정의 클래스를 만들고 원하는 속성을 정의하십시오. 그런 다음 UITextFieldDelegate를 사용하여 사용자 정의 클래스를 확장하고 원하는 곳 어디에서나 사용할 수 있습니다. –

답변

0

우선 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 당신이 필요로하는 키보드 유형을 표시하여 원하는 문자의 유형을 나타냅니다이라고 할 수 있습니다.