本文分享一種實作「驗證碼/密碼逐格輸入」的具體做法,重點在於把輸入框拆成獨立的格子,並能隨時在明文數字與圓點密文之間切換。
UIView 的容器視圖。textField、backgroundImageView、label。drawRect: 中繪製。secureTextEntry 屬性決定顯示真實數字或圓點。三個子控件各司其職:
視圖階層如下:

vertificationCodeInputViewtextFieldbackgroundImageViewlabel
層級上有個硬性要求:label 必須在最上層才能看得到內容;背景圖必須在 label 之下,且不能遮住它。
密碼模式(圓點):

驗證碼模式(明文數字):


@interface IDVertificationCodeInputView : UIView /** 背景圖片 */ @property (nonatomic, copy) NSString *backgroudImageName; /** 驗證碼/密碼位數 */ @property (nonatomic, assign) NSInteger numberOfVertificationCode; /** 是否以密文顯示 */ @property (nonatomic, assign) bool secureTextEntry; /** 目前的驗證碼/密碼內容 */ @property (nonatomic, copy) NSString *vertificationCode; @end
@interface IDVertificationCodeInputView () <UITextFieldDelegate> /** 取得鍵盤輸入用,實際不顯示 */ @property (nonatomic, strong) UITextField *textField; /** 背景圖 */ @property (nonatomic, strong) UIImageView *backgroundImageView; /** 實際顯示內容的 label */ @property (nonatomic, strong) IDLabel *label; @end
@interface IDLabel : UILabel /** 位數 */ @property (nonatomic, assign) NSInteger numberOfVertificationCode; /** 是否密文顯示 */ @property (nonatomic, assign) bool secureTextEntry; @end
預設四位、建立 textField 與 label。此處把容器背景設為透明,讓可見範圍等同背景圖的範圍:
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// 透明背景,讓可見範圍等於 backgroundImageView 的範圍
self.backgroundColor = [UIColor clearColor];
// 預設四位
self.numberOfVertificationCode = 4;
/* 用來叫出鍵盤的 textField */
self.textField = [[UITextField alloc] initWithFrame:self.bounds];
// 隱藏起來,改由點擊容器時成為第一回應者來彈出鍵盤
self.textField.hidden = YES;
self.textField.keyboardType = UIKeyboardTypeNumberPad;
self.textField.delegate = self;
// 放到最底層
[self insertSubview:self.textField atIndex:0];
/* 顯示用的 label */
self.label = [[IDLabel alloc] initWithFrame:self.bounds];
self.label.numberOfVertificationCode = self.numberOfVertificationCode;
self.label.secureTextEntry = self.secureTextEntry;
self.label.font = self.textField.font;
[self addSubview:self.label];
}
return self;
}
若設定了背景圖,就把背景圖插到 label 之下,避免遮住內容:
- (void)setBackgroudImageName:(NSString *)backgroudImageName {
_backgroudImageName = backgroudImageName;
self.backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds];
self.backgroundImageView.image = [UIImage imageNamed:self.backgroudImageName];
// 插到 label 後面,避免遮擋顯示
[self insertSubview:self.backgroundImageView belowSubview:self.label];
}
位數與密文開關則要同步給 label(此時 label 必定已建立):
- (void)setNumberOfVertificationCode:(NSInteger)numberOfVertificationCode {
_numberOfVertificationCode = numberOfVertificationCode;
self.label.numberOfVertificationCode = _numberOfVertificationCode;
}
- (void)setSecureTextEntry:(bool)secureTextEntry {
_secureTextEntry = secureTextEntry;
self.label.secureTextEntry = _secureTextEntry;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.textField becomeFirstResponder];
}
在 shouldChangeCharactersInRange 中攔截每一次輸入,超過位數就拒絕,遇到刪除鍵則退回一格:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
if (string.length != 0) {
// 非刪除:檢查是否已達指定位數
if (textField.text.length < self.numberOfVertificationCode) {
self.label.text = [textField.text stringByAppendingString:string];
self.vertificationCode = self.label.text;
return YES;
} else {
return NO;
}
} else {
// 刪除:移除最後一個字元
self.label.text = [textField.text substringToIndex:textField.text.length - 1];
self.vertificationCode = self.label.text;
return YES;
}
}
文字一變就主動觸發重繪:
- (void)setText:(NSString *)text {
[super setText:text];
[self setNeedsDisplay];
}
把寬度平均切成 N 份,每一格置中繪製;密文時畫圓點,明文時畫字元:
- (void)drawRect:(CGRect)rect {
// 每一格的寬與高
float width = rect.size.width / (float)self.numberOfVertificationCode;
float height = rect.size.height;
for (int i = 0; i < self.text.length; i++) {
CGRect tempRect = CGRectMake(i * width, 0, width, height);
if (self.secureTextEntry) {
// 密碼模式:畫圓點
UIImage *dotImage = [UIImage imageNamed:@"dot"];
CGPoint dotStartPoint = CGPointMake(
width * i + (width - dotImage.size.width) / 2.0,
(tempRect.size.height - dotImage.size.height) / 2.0);
[dotImage drawAtPoint:dotStartPoint];
} else {
// 驗證碼模式:畫數字
NSString *charecterString =
[NSString stringWithFormat:@"%c", [self.text characterAtIndex:i]];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
attributes[NSFontAttributeName] = self.font;
// 先量出尺寸,才能置中(不能直接從 tempRect 中點開始畫)
CGSize characterSize = [charecterString sizeWithAttributes:attributes];
CGPoint drawStartPoint = CGPointMake(
width * i + (width - characterSize.width) / 2.0,
(tempRect.size.height - characterSize.height) / 2.0);
[charecterString drawAtPoint:drawStartPoint withAttributes:attributes];
}
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
self.vertificationCodeInputView =
[[IDVertificationCodeInputView alloc] initWithFrame:CGRectMake(50, 250, 200, 45)];
self.vertificationCodeInputView.backgroudImageName = @"1";
// 驗證碼模式(顯示數字);改成 YES 即為密碼模式
self.vertificationCodeInputView.secureTextEntry = NO;
[self.view addSubview:self.vertificationCodeInputView];
}
需要取值時直接讀屬性即可:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%@", self.vertificationCodeInputView.vertificationCode);
}