Allow only alphanumeric characters for a UITextField

前端 未结 7 969
野性不改
野性不改 2020-11-27 17:44

How would I go about allowing inputting only alphanumeric characters in an iOS UITextField?

7条回答
  •  情话喂你
    2020-11-27 18:23

    Use the UITextFieldDelegate method -textField:shouldChangeCharactersInRange:replacementString: with an NSCharacterSet containing the inverse of the characters you want to allow. For example:

    // in -init, -initWithNibName:bundle:, or similar
    NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];
    
    - (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
    {
        return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
    }
    
    // in -dealloc
    [blockedCharacters release];
    

    Note that you’ll need to declare that your class implements the protocol (i.e. @interface MyClass : SomeSuperclass ) and set the text field’s delegate to the instance of your class.

提交回复
热议问题