IOS实现输入验证码、密码按位分割(二)

2020-01-14 18:45:20刘景俊


@interface IDVertificationCodeInputView () <UITextFieldDelegate>
/**用于获取键盘输入的内容,实际不显示*/
@property (nonatomic, strong) UITextField *textField;
/**验证码/密码输入框的背景图片*/
@property (nonatomic, strong) UIImageView *backgroundImageView;
/**实际用于显示验证码/密码的label*/
@property (nonatomic, strong) IDLabel *label;
@end

2、IDLabel(编号“4”视图)的属性

公有属性


@interface IDLabel : UILabel
/**验证码/密码的位数*/
@property (nonatomic, assign) NSInteger numberOfVertificationCode;
/**控制验证码/密码是否密文显示*/
@property (nonatomic, assign) bool secureTextEntry;
@end

3、业务逻辑

vertificationCodeInputView的初始化

  • 设置验证码/密码的默认位数(4位),添加textField和label
    
    - (instancetype)initWithFrame:(CGRect)frame {
      if (self = [super initWithFrame:frame]) {
        // 设置透明背景色,保证vertificationCodeInputView显示的frame为backgroundImageView的frame
        self.backgroundColor = [UIColor clearColor];
        // 设置验证码/密码的位数默认为四位
        self.numberOfVertificationCode = 4;
        /* 调出键盘的textField */
        self.textField = [[UITextField alloc] initWithFrame:self.bounds];
        // 隐藏textField,通过点击IDVertificationCodeInputView使其成为第一响应者,来弹出键盘
        self.textField.hidden = YES;
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
        self.textField.delegate = self;
        // 将textField放到最后边
        [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;
    }
    
    • 若设置了背景图片,需要将backgroundImageView添加进vertificationCodeInputView
      
      - (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];
      }