gpt4 book ai didi

ios - 只允许 UITextField 的字母数字字符

转载 作者:IT王子 更新时间:2023-10-29 08:01:52 25 4
gpt4 key购买 nike

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

最佳答案

使用 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];

请注意,您需要声明您的类实现协议(protocol)(即 @interface MyClass : SomeSuperclass <UITextFieldDelegate> )并设置文本字段的 delegate到您类(class)的实例。

关于ios - 只允许 UITextField 的字母数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com