UITextFiled 的运行时属性

Runtime Attribute of UITextFiled

我的应用程序中有很多 UITextField。

我不想让用户在这些文本字段中输入特殊字符。

我知道,我可以使用 shouldChangeCharactersInRange UITextFiled 的委托方法并验证它,但是这种方法对于 5-8 个 UITextFiled 是可行的,而不是 15-20 个。

我想使用 RuntimeAttributesUICategory 验证那些 (15-20) UITextFileds如下链接:-

http://johannesluderschmidt.de/category-for-setting-maximum-length-of-text-in-uitextfields-on-ios-using-objective-c/3209/

http://spin.atomicobject.com/2014/05/30/xcode-runtime-attributes/

我尝试创建 UITextFiled 的 UICategory,如下所示:-

UITextField+RunTimeExtension.h

@interface UITextField (RunTimeExtension)

@property(nonatomic,assign) BOOL *isAllowedSpecialCharacters;

@end

UITextField+RunTimeExtension.m

-(void)setIsAllowedSpecialCharacters:(BOOL *)isAllowedSpecialCharacters{

-(BOOL)isIsAllowedSpecialCharacters{
    if(self.isAllowedSpecialCharacters){
        NSCharacterSet *characterSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

        NSString *filtered = [[self.text componentsSeparatedByCharactersInSet:characterSet]  componentsJoinedByString:@""];

        return [self.text isEqualToString:filtered] || [self.text isEqualToString:@" "];
    }else{
        return NO;
    }
}

并在 RuntimeAttribute 中添加此属性,如下图所示:

但是没用,如果这个属性被选中了。

为什么不创建自定义文本字段 MyCustomTextField extends UITextField 并在需要时使用此自定义文本字段?

如果您需要更多详细信息,请告诉我。

您可以使用以下自定义 class 来满足您的所有要求。它使用正则表达式来验证 textField 您可以编辑它们以根据您的正则表达式处理 shouldChangeCharactersInRange

https://github.com/tomkowz/TSValidatedTextField

你的代码有很多错误。请参阅我的更正答案。

UITextField+SpecialCharacters.h

#import <UIKit/UIKit.h>

@interface UITextField (SpecialCharacters)

@property(nonatomic,assign) NSNumber *allowSpecialCharacters;
//here you were using BOOL *

@end

UITextField+SpecialCharacters.m

#import "UITextField+SpecialCharacters.h"
#import <objc/runtime.h>

@implementation UITextField (SpecialCharacters)

static void *specialCharKey;

-(void) setAllowSpecialCharacters:(NSNumber *)allowSpecialCharacters{

    objc_setAssociatedObject(self, &specialCharKey, allowSpecialCharacters, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

-(NSNumber *) allowSpecialCharacters{

    return objc_getAssociatedObject(self, &specialCharKey);
}

@end

Always set the names for getter and setter as per the standards.

在您的 ViewController 中,为文本字段设置委托并根据您的要求实施以下委托方法:

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([textField.allowSpecialCharacters boolValue]){
        NSCharacterSet *characterSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

        NSString *filtered = [[textField.text componentsSeparatedByCharactersInSet:characterSet]  componentsJoinedByString:@""];

        return [textField.text isEqualToString:filtered] || [textField.text isEqualToString:@" "];
    }else{
        return NO;
    }
}

在storyboard/nib中,您应该像在快照中一样设置运行时属性。您可以根据需要将值设置为 1 或 0。

这在我这边运行良好。希望它能解决你的问题。谢谢。