27

iOSで英数字のみの入力を許可するにはどうすればよいUITextFieldですか?

4

7 に答える 7

63

-textField:shouldChangeCharactersInRange:replacementString:許可する文字の逆を含むNSCharacterSetでUITextFieldDelegateメソッドを使用します。例えば:

// 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];

クラスがプロトコルを実装していることを宣言し(つまり@interface MyClass : SomeSuperclass <UITextFieldDelegate>)、テキストフィールドdelegateをクラスのインスタンスに設定する必要があることに注意してください。

于 2011-09-24T20:52:57.747 に答える
12

Swift3バージョン

現在受け入れられている回答アプローチ:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Get invalid characters
    let invalidChars = NSCharacterSet.alphanumerics.inverted

    // Attempt to find the range of invalid characters in the input string. This returns an optional.
    let range = string.rangeOfCharacter(from: invalidChars)

    if range != nil {
        // We have found an invalid character, don't allow the change
        return false
    } else {
        // No invalid character, allow the change
        return true
    }
}

別の同等に機能するアプローチ:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Get invalid characters
    let invalidChars = NSCharacterSet.alphanumerics.inverted

    // Make new string with invalid characters trimmed
    let newString = string.trimmingCharacters(in: invalidChars)

    if newString.characters.count < string.characters.count {
        // If there are less characters than we started with after trimming
        // this means there was an invalid character in the input. 
        // Don't let the change go through
        return false
    } else {
        // Otherwise let the change go through
        return true
    }

}
于 2017-03-17T01:03:41.783 に答える
11

シンプルで実用的な答えを見つけて、共有したいと思います。

イベントEditingChangedのUITextFieldを次のIBActionに接続します

-(IBAction) editingChanged:(UITextField*)sender
{    
    if (sender == yourTextField)
    {
        // allow only alphanumeric chars
        NSString* newStr = [sender.text stringByTrimmingCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];

        if ([newStr length] < [sender.text length])
        {
            sender.text = newStr;
        }
    }
}
于 2011-09-25T14:28:16.337 に答える
11

これが私のやり方です:

// Define some constants:
#define ALPHA                   @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC                 @"1234567890"
#define ALPHA_NUMERIC           ALPHA NUMERIC

// Make sure you are the text fields 'delegate', then this will get called before text gets changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // This will be the character set of characters I do not want in my text field.  Then if the replacement string contains any of the characters, return NO so that the text does not change.
    NSCharacterSet *unacceptedInput = nil;

    // I have 4 types of textFields in my view, each one needs to deny a specific set of characters:
    if (textField == emailField) {
        //  Validating an email address doesnt work 100% yet, but I am working on it....  The rest work great!
        if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
        } else {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
        }
    } else if (textField == phoneField) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
    } else if (textField == fNameField || textField == lNameField) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
    } else {
        unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
    }

    // If there are any characters that I do not want in the text field, return NO.
    return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}

UITextFieldDelegateリファレンスもチェックしてください。

于 2011-09-24T20:48:27.677 に答える
6

Swiftの正規表現の方法:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
     if string.isEmpty {
         return true
     }
     let alphaNumericRegEx = "[a-zA-Z0-9]"
     let predicate = NSPredicate(format:"SELF MATCHES %@", alphaNumericRegEx)
     return predicate.evaluate(with: string)
}
于 2017-10-05T08:55:29.577 に答える
1

Swiftの場合:イベントEditingChangedのUITextFieldを次のIBActionに接続します。

@IBAction func ActionChangeTextPassport(sender:UITextField){
    if sender == txtPassportNum{
        let newStr = sender.text?.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
        if newStr?.characters.count < sender.text?.characters.count{
            sender.text = newStr
        }
    }
}
于 2016-10-02T08:28:11.743 に答える
0

メソッドを使用し、textField delegateメソッドtextFieldDidBeginEditingを使用し、文字shouldChangeCharactersInRangetextFieldDidEndEditing確認する必要があります。

ドキュメントについては、このリンクを参照してください。

于 2011-09-24T20:49:44.597 に答える