該例子主要利用策略模式來判斷UITextField是否滿足輸入要求,比如輸入的只能是數字,如果只是數字就沒有提示,如果有其他字符則提示出錯。驗證字母也是一樣。
首先,我們先定義一個抽象的策略類iputValidator。代碼如下:
InputValidator.h
//// InputValidator.h// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>static NSString * const InputValidationErrorDomain = @"InputValidationErrorDomain";@interface InputValidator : NSObject//實際驗證策略的存根方法-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;@end
InputValidator.m
//// InputValidator.m// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "InputValidator.h"@implementation InputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error{ if (error) { *error = nil; } return NO;}@end
這個就是一個策略基類,然后我們去創建兩個子類NumericInputValidator和AlphaInputValidator。具體代碼如下:
NumericIputValidator.h
//// NumericInputValidator.h// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "InputValidator.h"@interface NumericInputValidator : InputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;@end
NumericIputValidator.m
//// NumericInputValidator.m// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "NumericInputValidator.h"@implementation NumericInputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error{ NSError *regError = nil; //使用配置的NSRegularExPRession對象,檢查文本框中數值型的匹配次數。 //^[0-9]*$:意思是從行的開頭(表示為^)到結尾(表示為$)應該有數字集(標示為[0-9])中的0或者更多個字符(表示為*) NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])]; //如果沒有匹配,就返回錯誤和NO if (numberOfMatches==0) { if (error != nil) { NSString *description = NSLocalizedString(@"Input Validation Faild", @""); NSString *reason = NSLocalizedString(@"The input can contain only numerical values", @""); NSArray *objArray = [NSArray arrayWithObjects:description,reason, nil]; NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey ,nil]; NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray]; *error = [NSError errorWithDomain:InputValidationErrorDomain code:1001 userInfo:userInfo]; } return NO; } return YES;}@end
AlphaInputValidator.h
//// AlphaInputValidator.h// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "InputValidator.h"@interface AlphaInputValidator : InputValidator- (BOOL)validateInput:(UITextField *)input error:(NSError **)error;@end
AlphaInputValidator.m
//// AlphaInputValidator.m// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "AlphaInputValidator.h"@implementation AlphaInputValidator-(BOOL)validateInput:(UITextField *)input error:(NSError **)error{ NSError *regError = nil; //使用配置的NSRegularExpression對象,檢查文本框中數值型的匹配次數。 //^[0-9]*$:意思是從行的開頭(表示為^)到結尾(表示為$)應該有數字集(標示為[0-9])中的0或者更多個字符(表示為*) NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])]; //如果沒有匹配,就返回錯誤和NO if (numberOfMatches==0) { if (error != nil) { NSString *description = NSLocalizedString(@"Input Validation Faild", @""); NSString *reason = NSLocalizedString(@"The input can contain only letters ", @""); NSArray *objArray = [NSArray arrayWithObjects:description,reason, nil]; NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey ,nil]; NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray]; *error = [NSError errorWithDomain:InputValidationErrorDomain code:1002 userInfo:userInfo]; } return NO; } return YES;}@end
他們兩個都是InputValidator的子類。然后再定義一個CustomTextField:
CustomTextField.h
//// CustomTextField.h// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import <UIKit/UIKit.h>@class InputValidator;@interface CustomTextField : UITextField@property(nonatomic,strong)InputValidator *inputValidator;-(BOOL)validate;@end
CustomTextField.m
//// CustomTextField.m// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "CustomTextField.h"#import "InputValidator.h"@implementation CustomTextField-(BOOL)validate { NSError *error = nil; BOOL validationResult = [_inputValidator validateInput:self error:&error]; if (!validationResult) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription] message:[error localizedFailureReason] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles: nil]; [alertView show]; } return validationResult;}@end
最后在ViewController中測試是否完成驗證
ViewController.m
//// ViewController.m// StrategyDemo//// Created by zhanggui on 15/8/7.// Copyright (c) 2015年 zhanggui. All rights reserved.//#import "ViewController.h"#import "CustomTextField.h"#import "NumericInputValidator.h"#import "AlphaInputValidator.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; _numberTextField.inputValidator = [NumericInputValidator new]; _letterTextField.inputValidator = [AlphaInputValidator new]; // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}#pragma mark - ValidButtonMehtod- (IBAction)validNumAction:(id)sender { [_numberTextField validate];}- (IBAction)validLetterAction:(id)sender { [_letterTextField validate];}@end
結果:當我們輸入的不滿足條件的時候就會顯示提示信息,而滿足條件就不會有任何提示。
新聞熱點
疑難解答