UITextField shouldChangeCharactersinRange 作为外部函数

UITextField shouldChangeCharactersinRange as external function

我想验证多个视图控制器的 UITextField 输入。以下作品:

validate.h

#import <UIKit/UIKit.h>

@interface validate : UITextField <UITextFieldDelegate>
@end

validate.m

#import "validate.h"

@implementation validate

viewController.h

#import <UIKit/UIKit.h>
#include "limiteTextField.h"

@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet limiteTextField *myTextField;
@end

viewController.m

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController  

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
 //my code for validating 
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _myTextField.delegate=self;

我希望能够将 shouldChangeCharactersInRange 用作外部函数,这样就不必为每个视图控制器重写所有代码。

I want to be able to use the shouldChangeCharactersInRange as an external function so don't have to rewrite all its code for each view controller.

那就这样做吧。这是一个委托方法。任何东西都可以是代表。您是将文本字段的委托设置为不同视图控制器的人!如果你不想那样做,那就别做。有一些单一的持久对象,或至少相同 class 的多个实例,并使 that 成为文本字段的委托。现在所有文本字段都可以使用同一个委托,它只有一个 shouldChangeCharactersInRange.

的实现

一种方法是使用单例创建某种验证器 class 并将其指定为文本字段委托:

TextFieldValidator.h

#import <UIKit/UIKit.h>

@interface TextFieldValidator : NSObject <UITextFieldDelegate>

+ (instancetype)sharedValidator;

@end

TextFieldValidator.m

#import "TextFieldValidator.h"

@implementation TextFieldValidator

+ (instancetype)sharedValidator {
    static TextFieldValidator *sharedValidator = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedValidator = [[self alloc] init];
    });
    return sharedValidator;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *allowedCharacters = [NSCharacterSet decimalDigitCharacterSet];
    return [[textField.text stringByReplacingCharactersInRange:range withString:string] rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound;
}

@end

SomeViewController.m

// [...]

self.textField.delegate = [TextFieldValidator sharedValidator];

// [...]