ios – UITextFiled的运行时属性

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

我不想让用户输入那些文本字段的特殊字符.

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

我想使用RuntimeAttributes和UICategory验证那些(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中添加此属性,如下图所示:

但是如果检查了这个属性是不行的.

最佳答案 您的代码中存在许多错误.请参阅我的答案以进行更正.

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中,为textfield设置委托,并根据您的要求实现以下委托方法:

-(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.

这对我来说很好.希望它能解决你的问题.谢谢.

点赞