文本字段的运行时属性

问题描述 投票:4回答:3

我的应用程序中有很多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/

我试着创建一个文本字段类别如下: -

的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中添加此属性,如下图所示:

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

ios objective-c uitextfield uitextfielddelegate
3个回答
1
投票

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

的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

始终按照标准设置getter和setter的名称。

在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。

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


1
投票

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

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


0
投票

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

https://github.com/tomkowz/TSValidatedTextField

© www.soinside.com 2019 - 2024. All rights reserved.