UITextField 仅允许使用字母数字字符

发布于 2024-12-06 20:55:27 字数 55 浏览 0 评论 0原文

我将如何允许在 iOS UITextField 中仅输入字母数字字符?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

拔了角的鹿 2024-12-13 20:55:27

将 UITextFieldDelegate 方法 -textField:shouldChangeCharactersInRange:replacementString: 与包含您想要允许的字符反转的 NSCharacterSet 结合使用。例如:

// 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)并将文本字段的 delegate 设置为你的班级的实例。

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 <UITextFieldDelegate>) and set the text field’s delegate to the instance of your class.

月牙弯弯 2024-12-13 20:55:27

Swift 3 版本

当前接受的答案方法:

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
    }

}

Swift 3 version

Currently accepted answer approach:

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
    }
}

Another equally functional approach:

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
    }

}
蘸点软妹酱 2024-12-13 20:55:27

这就是我的做法:

// 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 参考 也是如此。

This is how I do it:

// 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);
}

Check out the UITextFieldDelegate Reference too.

娇纵 2024-12-13 20:55:27

我找到了一个简单且有效的答案并想分享:

将事件 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;
        }
    }
}

I found a simple and working answer and want to share:

connect your UITextField for the event EditingChanged to following 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;
        }
    }
}
望喜 2024-12-13 20:55:27

Swift 中的 RegEx 方式:

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)
}

The RegEx way in 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)
}
記柔刀 2024-12-13 20:55:27

对于斯威夫特:
将 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
        }
    }
}

For Swift:
Connect your UITextField for the event EditingChanged to following 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
        }
    }
}
另类 2024-12-13 20:55:27

您必须使用 textField delegate 方法,并使用方法 textFieldDidBeginEditingshouldChangeCharactersInRangetextFieldDidEndEditing 来检查人物。

请参阅此链接了解文档。

You will have to use the textField delegate methods, and use methods textFieldDidBeginEditing, shouldChangeCharactersInRange and textFieldDidEndEditing to check for the characters.

Please refer to this link for the documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文