您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 自製驗證碼輸入框:逐格顯示與密文切換

編輯:iOS 開發綜合

本文分享一種實作「驗證碼/密碼逐格輸入」的具體做法,重點在於把輸入框拆成獨立的格子,並能隨時在明文數字與圓點密文之間切換。

一、實作思路

  • 自訂一個繼承自 UIView 的容器視圖。
  • 在裡面放三個子控件:textField、backgroundImageView、label。
  • 把內容「畫」到 label 上,而不是靠 label 本身的文字排版,因此需要自訂 label 並在 drawRect: 中繪製。
  • 用一個 secureTextEntry 屬性決定顯示真實數字或圓點。

三個子控件各司其職:

  • textField:只負責叫出鍵盤並接收輸入,本身隱藏不顯示。
  • backgroundImageView:負責呈現帶有分隔線的背景圖。
  • label:負責實際顯示驗證碼或密碼。

視圖階層如下:

  • 編號 1:父視圖 vertificationCodeInputView
  • 編號 2:子視圖 textField
  • 編號 3:子視圖 backgroundImageView
  • 編號 4:子視圖 label

層級上有個硬性要求:label 必須在最上層才能看得到內容;背景圖必須在 label 之下,且不能遮住它。

二、成果預覽

密碼模式(圓點):

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

三、程式結構

1. 容器視圖的對外屬性

@interface IDVertificationCodeInputView : UIView
/** 背景圖片 */
@property (nonatomic, copy) NSString *backgroudImageName;
/** 驗證碼/密碼位數 */
@property (nonatomic, assign) NSInteger numberOfVertificationCode;
/** 是否以密文顯示 */
@property (nonatomic, assign) bool secureTextEntry;
/** 目前的驗證碼/密碼內容 */
@property (nonatomic, copy) NSString *vertificationCode;
@end

2. 容器視圖的內部屬性

@interface IDVertificationCodeInputView () <UITextFieldDelegate>
/** 取得鍵盤輸入用,實際不顯示 */
@property (nonatomic, strong) UITextField *textField;
/** 背景圖 */
@property (nonatomic, strong) UIImageView *backgroundImageView;
/** 實際顯示內容的 label */
@property (nonatomic, strong) IDLabel *label;
@end

3. 自訂 IDLabel 的對外屬性

@interface IDLabel : UILabel
/** 位數 */
@property (nonatomic, assign) NSInteger numberOfVertificationCode;
/** 是否密文顯示 */
@property (nonatomic, assign) bool secureTextEntry;
@end

4. 初始化與業務邏輯

預設四位、建立 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;
}

5. 彈出鍵盤並接收輸入

- (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;
    }
}

6. 在 IDLabel 中逐格繪製

文字一變就主動觸發重繪:

- (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];
        }
    }
}

7. 使用方式

- (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);
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved