xcode 在 UITextView 中只允许字母数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16147042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:16:01  来源:igfitidea点击:

Allow only alpha numeric characters in UITextView

objective-cxcodeuitextviewnscharacterset

提问by user2268539

Is there anyway i can allow user to enter only alpha numeric characters in a text view and no other character.

无论如何,我可以允许用户在文本视图中仅输入字母数字字符,而不能输入其他字符。

EDIT:

编辑:

Tried,

试过了,

if ([_txtView.text rangeOfCharacterFromSet:alphaSet].location != NSNotFound)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"Only alpha numeric characters are allowed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;

    }

but this only works for some of the times

但这仅适用于某些时候

Thanks!!

谢谢!!

回答by RJR

You can achieve that using [[[NSCharacterSet alphanumericCharacterSet] invertedSet]. This method will return a character set containing only characters that don't exist in the receiver.

您可以使用 [[[NSCharacterSet alphanumericCharacterSet] reverseSet] 来实现。此方法将返回一个仅包含接收器中不存在的字符的字符集。

NSCharacterSet *charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

//Conform UITextField delegate and implement this method.

//符合 UITextField 委托并实现此方法。

 - (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
 {
    return ([characters rangeOfCharacterFromSet:charactersToBlock].location == NSNotFound);
 }

回答by DharaParekh

Try this:

尝试这个:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
            if (textField == txtWebsite) {
                    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "];

                    if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
                        return YES;
                    }
                    else {
                        return NO;
                    }
            }
            else {
                    return YES;
            }
    }

write code in delegate method of uitextfield.

在 uitextfield 的委托方法中编写代码。

回答by user1113101

set delegate for textview and override/implement test should change in range method

为 textview 和覆盖/实现测试设置委托应该在范围方法中改变

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 
{
     NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
     BOOL valid = [[text stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
     return valid;    
}

回答by Rishi

Equivalent Swift 3 version of the answer provided by @user1113101

@user1113101 提供的等效 Swift 3 版本的答案

Though it's late to answer and there are other simple and great approaches, but this answer might be useful to someone.

虽然回答晚了,还有其他简单而伟大的方法,但这个答案可能对某人有用。

This is simple and worked like a charm for me.

这很简单,对我来说就像一种魅力。

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    /// 1. replacementText is NOT empty means we are entering text or pasting text: perform the logic
    /// 2. replacementText is empty means we are deleting text: return true
    if text.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics

        let unwantedStr = text.trimmingCharacters(in: allowedCharacters)
        return unwantedStr.characters.count == 0
    }

    return true
}

Note: This will work for pasting strings into the text field as well. Pasted string will not be displayed in text field if it contains any unwanted characters.

注意:这也适用于将字符串粘贴到文本字段中。如果粘贴的字符串包含任何不需要的字符,则不会在文本字段中显示。

回答by iCoder



// Add this in ViewDidLoad or any init method NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];

// 在 ViewDidLoad 或任何初始化方法中添加 NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] reverseSet] retain];

then Set your textfield's delegate in nib file .

然后在 nib 文件中设置文本字段的委托。

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}

Or there is another way in shouldChangeCharactersInRangemethod. You can check

或者有另一种shouldChangeCharactersInRange方法。你可以检查

{
    NSString *stringPlace = @"[a-z  A-Z]*";

    NSPredicate *testPlace = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringPlace]; 
        BOOL matches = [testPlace evaluateWithObject:string];

        if (!matches && string.length > 5)
        {
            return NO;
        }
    return YES;
}