如何禁用 UITextField 中的字母字符?

发布于 2024-10-13 00:21:36 字数 59 浏览 2 评论 0原文

在我的应用程序中,我需要允许用户仅输入数字。 我如何允许 UITextField 仅接收来自用户的数字?

In my application i need to allow users input only numbers.
How can i allow UITextField to receive only numbers from user?

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

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

发布评论

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

评论(10

无悔心 2024-10-20 00:21:36

本示例中的字符是允许的,因此如果您不希望用户使用某个字符,请将其从 myCharSet 中排除。

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }

    return YES;
} 

The characters in this examples are allowed, so if you dont want the user to use a character, exclude it from myCharSet.

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }

    return YES;
} 
拍不死你 2024-10-20 00:21:36

我更喜欢以下解决方案,它实际上可以防止除数字和退格键之外的任何输入。出于某种原因,退格键由空字符串表示,除非空字符串返回 YES,否则无法使用。当用户输入数字以外的字符时,我还会弹出一个警报视图。

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    if (string.length == 0) {
        return YES;
    }
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if ([myCharSet characterIsMember:c]) {
            return YES;
        }
    }
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Invalid Input" message:@"Only numbers are allowed for participant number." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [av show];
    return NO;
}

I prefer the following solution that actually prevents any any input except from numbers and backspace. Backspace for some reason is represented by an empty string and could not be used unless empty string returns YES. I also popup an alert view when the user enters a character other that numbers.

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    if (string.length == 0) {
        return YES;
    }
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if ([myCharSet characterIsMember:c]) {
            return YES;
        }
    }
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Invalid Input" message:@"Only numbers are allowed for participant number." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [av show];
    return NO;
}
箜明 2024-10-20 00:21:36

这可能是最干净、最简单的解决方案,只允许正数或负数。这也允许退格。

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789"];

    if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){

        return YES;

    }

    return NO;

}

This is perhaps the cleanest, simplest solution to allow only positive or negative numbers. This also allows backspace.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789"];

    if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){

        return YES;

    }

    return NO;

}
半暖夏伤 2024-10-20 00:21:36

您可以做的一件事是显示数字键盘,并在文本字段旁边或其他地方添加一个动态按钮来隐藏键盘。

One thing you can do is to show the numbers key pad and beside text field or some where else add a dynamic button to hide the keyboard.

远昼 2024-10-20 00:21:36

你们可能会发火..但这对我有用..只有数字(包括负数)和退格键。

NSCharacterSet *validCharSet;

if (range.location == 0) 
    validCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789-."];
else
    validCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];

if ([[string stringByTrimmingCharactersInSet:validCharSet] length] > 0 ) return NO;  //not allowable char


NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSNumber* candidateNumber;

NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];

range = NSMakeRange(0, [candidateString length]);

[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];

if  (candidateNumber == nil ) {

    if  (candidateString.length <= 1) 
        return YES;
    else
        return NO;
}

return YES;

you guys might flame.. but this worked for me.. only numbers (including negatives), and backspace.

NSCharacterSet *validCharSet;

if (range.location == 0) 
    validCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789-."];
else
    validCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];

if ([[string stringByTrimmingCharactersInSet:validCharSet] length] > 0 ) return NO;  //not allowable char


NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSNumber* candidateNumber;

NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];

range = NSMakeRange(0, [candidateString length]);

[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];

if  (candidateNumber == nil ) {

    if  (candidateString.length <= 1) 
        return YES;
    else
        return NO;
}

return YES;
<逆流佳人身旁 2024-10-20 00:21:36

这是我的解决方案,使用方法 isSupersetOfSet: 应用集合代数,这也不允许粘贴带有无效字符的文本:

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (string.length == 0 || [_numericCharSet isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:string]]) {
        return YES;
    }
    else {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Invalid Input"
                                                     message:@"Only numeric input allowed."
                                                    delegate:self
                                           cancelButtonTitle:@"Close"
                                           otherButtonTitles:nil];
        [av show];
        return NO;
    }
}

注意:根据 Apple 开发者库,最好缓存静态NSCharacterSet 而不是一次又一次地创建它(这里是 _numericCharSet)。

不过,我更喜欢让用户输入任何字符并验证当 textField 尝试退出第一响应者时调用的方法 textFieldShouldEndEditing: 中的值。
通过这种方式,用户可以粘贴任何文本(可能由字母和数字混合组成)并将其整理到我的文本字段中。用户不喜欢看到他们的行动受到限制。

Here is my solution applying algebra of sets with the method isSupersetOfSet: This also doesn't allow pasting text with invalid characters:

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (string.length == 0 || [_numericCharSet isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:string]]) {
        return YES;
    }
    else {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Invalid Input"
                                                     message:@"Only numeric input allowed."
                                                    delegate:self
                                           cancelButtonTitle:@"Close"
                                           otherButtonTitles:nil];
        [av show];
        return NO;
    }
}

Note: according to Apple Developer Library, It's preferable cache the static NSCharacterSet than to create it again and again (here _numericCharSet).

However I prefer to let the user to input any character and validate the value in the method textFieldShouldEndEditing: called when the textField tries to resign first responder.
In this manner the user can paste any text (maybe composed with a mix of letters and numbers) and tidy up it in my textFields. The users do not like to see limited their actions.

一场春暖 2024-10-20 00:21:36

在斯威夫特

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 2 {  //your textField
        let invalid = NSCharacterSet(charactersInString: "aeiou")  //characters to block
        if let range = string.rangeOfCharacterFromSet(invalid) {
            return false
        }
    }

    return true
}

In Swift

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 2 {  //your textField
        let invalid = NSCharacterSet(charactersInString: "aeiou")  //characters to block
        if let range = string.rangeOfCharacterFromSet(invalid) {
            return false
        }
    }

    return true
}
别挽留 2024-10-20 00:21:36

这是一个快速示例,

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

    var disabledCharacters:NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
        for (var i:Int = 0; i < count(string); ++i) {
            var c = (string as NSString).characterAtIndex(i)
            if (disabledCharacters.characterIsMember(c)) {
                println("Can't use that character dude :/")
                return false
            }
        }

    return true
}

不要忘记将 UITextFieldDelegate 添加到您的 UIViewController 中。

Here is a swift example

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

    var disabledCharacters:NSCharacterSet = NSCharacterSet(charactersInString: "0123456789")
        for (var i:Int = 0; i < count(string); ++i) {
            var c = (string as NSString).characterAtIndex(i)
            if (disabledCharacters.characterIsMember(c)) {
                println("Can't use that character dude :/")
                return false
            }
        }

    return true
}

Don't forget to add UITextFieldDelegate to your UIViewController as well.

2024-10-20 00:21:36
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    char *x = (char*)[string UTF8String];
    //NSLog(@"char index is %i",x[0]);
    if([string isEqualToString:@"-"] || [string isEqualToString:@"("] || [string isEqualToString:@")"] || [string isEqualToString:@"0"] || [string isEqualToString:@"1"] ||  [string isEqualToString:@"2"] ||  [string isEqualToString:@"3"] ||  [string isEqualToString:@"4"] ||  [string isEqualToString:@"5"] ||  [string isEqualToString:@"6"] ||  [string isEqualToString:@"7"] ||  [string isEqualToString:@"8"] ||  [string isEqualToString:@"9"] || x[0]==0 || [string isEqualToString:@" "]) {

    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 14) ? NO : YES;
} else {
    return NO;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    char *x = (char*)[string UTF8String];
    //NSLog(@"char index is %i",x[0]);
    if([string isEqualToString:@"-"] || [string isEqualToString:@"("] || [string isEqualToString:@")"] || [string isEqualToString:@"0"] || [string isEqualToString:@"1"] ||  [string isEqualToString:@"2"] ||  [string isEqualToString:@"3"] ||  [string isEqualToString:@"4"] ||  [string isEqualToString:@"5"] ||  [string isEqualToString:@"6"] ||  [string isEqualToString:@"7"] ||  [string isEqualToString:@"8"] ||  [string isEqualToString:@"9"] || x[0]==0 || [string isEqualToString:@" "]) {

    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 14) ? NO : YES;
} else {
    return NO;
}
}
沉溺在你眼里的海 2024-10-20 00:21:36

这个线程有点旧,但为了参考,我将在 swift 3 中留下一个解决方案。该解决方案将结合 decimalDigits 和实际的小数。您可以将任何您想要的组合放在一起,但对于我的情况来说,这就是要求。

// instantiate a mutable character set
let characterSet = NSMutableCharacterSet()
// assign the needed character set
characterSet.formUnion(with: NSCharacterSet.decimalDigits)
// only need the decimal character added to the character set
characterSet.addCharacters(in: ".")
// invert and return false if it's anything other than what we're looking for
if string.rangeOfCharacter(from: characterSet.inverted) != nil {
    return false
}

This thread is a little old, but for the sake of reference I am going to leave a solution in swift 3. This solution will combine decimalDigits and the actual decimal. You can put together whatever combination you'd like, but for my case this is what the requirements were.

// instantiate a mutable character set
let characterSet = NSMutableCharacterSet()
// assign the needed character set
characterSet.formUnion(with: NSCharacterSet.decimalDigits)
// only need the decimal character added to the character set
characterSet.addCharacters(in: ".")
// invert and return false if it's anything other than what we're looking for
if string.rangeOfCharacter(from: characterSet.inverted) != nil {
    return false
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文