说到实现一个弹窗,我们很多人第一反应就会想到使用系统的 UIAlertController
。然后我们要一个带数字密码的弹窗,我们或许就会这样写:
在 @interface
声明密码框:
/**
密码框
*/
@property (nonatomic, weak) UITextField *txtPassword;
弹窗的实现代码:
UIAlertController *alterControl = [UIAlertController alertControllerWithTitle:@"请输入密码" message:nil preferredStyle:UIAlertControllerStyleAlert];
// 输入框
[alterControl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
// 配置输入框
[textField setFont:[UIFont systemFontOfSize:15]];
[textField setTextColor:[UIColor colorWithWhite:51/255.0 alpha:1.0]];
[textField setSecureTextEntry:YES];
self.txtPassword = textField;
}];
// 取消
UIAlertAction *actionCacnel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alterControl addAction:actionCacnel];
// 确认
UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 输入框的内容
NSLog(@"%@", self.txtPassword.text);
}];
[alterControl addAction:actionConfirm];
[self presentViewController:alterControl animated:YES completion:nil];
代码运行后实现的效果:
从图上可以看出密码的圆点都靠在左边,而且这个布局也不怎么好看。而且这里还有一个很不切合实际的地方,那就是当我们点击了任意一个按钮都会导致 UIAlertController
消失掉,这样的交互是一种糟糕的体验。
既然 UIAlertController
既不切合实际,布局又不美观,那我们只好选择自定义来实现了。我们看到现在市场上的密码弹窗,看上去是一个个小的 UITextField
排起来的,但是如果是这样的话,感觉有点太麻烦,后来在网上查了一下,发现有人将一个完全隐藏的 UITextView
做键盘输入响应,用一排 UILabel
做已经输入数字显示,用一个闪烁的动画作待输入光标。
这是该作者的原文地址 iOS自定义验证码输入框(4位或6位)
根据这个作者的文章结合项目的实际需要,做了一下适当的修改,封装成了一个叫 NumberCodeInputView
的工具类,具体代码如下:
在 NumberCodeInputView.h
头文件的代码:
#import
NS_ASSUME_NONNULL_BEGIN
/**
数字码处理
@param strNumberCode 数字码
*/
typedef void(^NumberCodeBlock)(NSString *strNumberCode);
/**
1~6位数字码弹窗
*/
@interface NumberCodeInputView : UIView
/**
初始化数字码弹窗
@param numberCount 数字位数 1~6
@param viewTitle 弹窗标题
@param cancelTitle 取消标题
@param confirmTitle 确认标题
@param complete 完成处理
@return 实例化对象
*/
- (instancetype)initWithNumberCount:(NSInteger)numberCount viewTitle:(NSString *)viewTitle cancelTitle:(NSString *)cancelTitle confirmTitle:(NSString *)confirmTitle complete:(NumberCodeBlock)complete;
/**
清空输入数字
*/
- (void)clearInputNumber;
/**
取消处理
*/
@property (nonatomic, copy) void(^cancelBlock)(void);
@end
NumberCodeInputView.m
的实现过程:
#import "NumberCodeInputView.h"
// 屏幕的宽和高
#define kScreen_Width [[UIScreen mainScreen] bounds].size.width
#define kScreen_Height [[UIScreen mainScreen] bounds].size.height
// 颜色
#define kColor33 [UIColor colorWithWhite:51/255.0 alpha:1.0]
#define kColorMain [UIColor colorWithRed:72/255.0 green:114/255.0 blue:190/255.0 alpha:1.0]
#define kColorShadow [UIColor colorWithWhite:27/255.0 alpha:0.68]
#define kColorBgGray [UIColor colorWithWhite:242/255.0 alpha:1.0]
@interface NumberCodeInputView ()
/**
数组数量
*/
@property (nonatomic, assign) NSInteger nNumberCount;
/**
字符串数组 0、弹窗标题 1、取消标题 2、确认标题
*/
@property (nonatomic, strong) NSArray *arrTitle;
/**
输入视图
*/
@property (nonatomic, weak) UITextView *txtvInput;
/**
输入数字隐藏的黑点
*/
@property (nonatomic, strong) NSArray *arrBlackPoint;
/**
闪动的光标
*/
@property (nonatomic, weak) CAShapeLayer *shapeCursor;
/**
完成处理
*/
@property (nonatomic, copy) NumberCodeBlock blockComplete;
@end
@implementation NumberCodeInputView
/**
初始化数字码弹窗
@param numberCount 数字位数 1~6
@param viewTitle 弹窗标题
@param cancelTitle 取消标题
@param confirmTitle 确认标题
@param complete 完成处理
@return 实例化对象
*/
- (instancetype)initWithNumberCount:(NSInteger)numberCount viewTitle:(NSString *)viewTitle cancelTitle:(NSString *)cancelTitle confirmTitle:(NSString *)confirmTitle complete:(NumberCodeBlock)complete {
self = [super initWithFrame:[UIScreen mainScreen].bounds];
if (self) {
if (numberCount < 1) {
self.nNumberCount = 1;
} else if(numberCount > 6) {
self.nNumberCount = 6;
} else {
self.nNumberCount = numberCount;
}
self.arrTitle = @[viewTitle, cancelTitle, confirmTitle];
self.blockComplete = complete;
[self initLayout];
[self.txtvInput becomeFirstResponder];
}
return self;
}
- (void)initLayout {
// 阴影背景
UIView *backShadow = [[UIView alloc] initWithFrame:self.frame];
[backShadow setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:0.1]];
[self addSubview:backShadow];
// 取消手势
UITapGestureRecognizer *tapCancel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction)];
[backShadow addGestureRecognizer:tapCancel];
// 主视图
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(kScreen_Width/2 - 142, kScreen_Height/2 - 90, 282, 160)];
[mainView setBackgroundColor:[UIColor whiteColor]];
[mainView setClipsToBounds:YES];
[mainView.layer setCornerRadius:5];
[self addSubview:mainView];
// 视图表头
UILabel *labTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 284, 44)];
[labTitle setTextColor:kColor33];
[labTitle setTextAlignment:NSTextAlignmentCenter];
[labTitle setText:self.arrTitle[0]];
[mainView addSubview:labTitle];
// 用于弹出键盘的输入视图
UITextView *txtvTemp = [[UITextView alloc] initWithFrame:CGRectMake(12, 44, 240, 70)];
[txtvTemp setBackgroundColor:[UIColor clearColor]];
[txtvTemp setTextColor:[UIColor clearColor]];
// 光标颜色
[txtvTemp setTintColor:[UIColor clearColor]];
[txtvTemp setKeyboardType:UIKeyboardTypeNumberPad];
[txtvTemp setDelegate:self];
[mainView addSubview:txtvTemp];
self.txtvInput = txtvTemp;
// 第一个数字的横坐标
CGFloat fOriginX = (294 - 45 * self.nNumberCount)/2;
NSMutableArray *arrmPoint = [NSMutableArray arrayWithCapacity:100];
for (int i = 0; i < self.nNumberCount; i++) {
// 黑点
UIView *pointView = [[UIView alloc] initWithFrame:CGRectMake(fOriginX + 10 + i * 45, 60, 15, 15)];
[pointView setBackgroundColor:kColor33];
[pointView setClipsToBounds:YES];
[pointView.layer setCornerRadius:pointView.frame.size.height/2];
[pointView setUserInteractionEnabled:NO];
[mainView addSubview:pointView];
[pointView setHidden:YES];
[arrmPoint addObject:pointView];
// 下划线
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(fOriginX + i * 45, CGRectGetMaxY(pointView.frame) + 15, 35, 1)];
[lineView setBackgroundColor:kColorBgGray];
[mainView addSubview:lineView];
}
self.arrBlackPoint = arrmPoint;
// 闪动的光标
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(fOriginX + 16.5, 57, 2, 26)];
CAShapeLayer *shapeTemp = [CAShapeLayer layer];
shapeTemp.path = path.CGPath;
shapeTemp.fillColor = kColor33.CGColor;
[shapeTemp addAnimation:[self opacityAnimation] forKey:@"kOpacityAnimation"];
[mainView.layer addSublayer:shapeTemp];
self.shapeCursor = shapeTemp;
// 取消、确认按钮
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 115, 284, 1)];
[lineView setBackgroundColor:kColorBgGray];
[mainView addSubview:lineView];
lineView = [[UIView alloc] initWithFrame:CGRectMake(142, 116, 1, 44)];
[lineView setBackgroundColor:kColorBgGray];
[mainView addSubview:lineView];
for (int i = 0; i < 2; i++) {
UIButton *btnItem = [[UIButton alloc] initWithFrame:CGRectMake(i * 142, 116, 142, 44)];
[btnItem setTitle:self.arrTitle[i + 1] forState:UIControlStateNormal];
[btnItem setTitleColor:kColorMain forState:UIControlStateNormal];
[btnItem.titleLabel setFont:[UIFont systemFontOfSize:15]];
if (i == 0) {
[btnItem addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
} else {
[btnItem addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
}
[mainView addSubview:btnItem];
}
}
// 闪动动画
- (CABasicAnimation *)opacityAnimation {
CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.fromValue = @(1.0);
opacityAnimation.toValue = @(0.0);
opacityAnimation.duration = 0.9;
opacityAnimation.repeatCount = HUGE_VALF;
opacityAnimation.removedOnCompletion = YES;
opacityAnimation.fillMode = kCAFillModeForwards;
opacityAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
return opacityAnimation;
}
/**
取消事件
*/
- (void)cancelAction {
if (self.cancelBlock) {
self.cancelBlock();
}
[self endEditing:YES];
[self removeFromSuperview];
}
/**
确认事件
*/
- (void)confirmAction {
if ([self.txtvInput.text length] < self.nNumberCount) {
NSString *strMessage = [NSString stringWithFormat:@"请输入%@位数字", @(self.nNumberCount)];
NSLog(@"%@", strMessage);
return;
}
NSString *strText;
if ([self.txtvInput.text length] == self.nNumberCount) {
strText = self.txtvInput.text;
} else {
strText = [self.txtvInput.text substringToIndex:self.nNumberCount];
}
NSLog(@"数字码: %@", strText);
if (self.blockComplete) {
self.blockComplete(strText);
}
[self endEditing:YES];
}
/**
清空输入数字
*/
- (void)clearInputNumber {
[self.txtvInput setText:@""];
[self textViewDidChange:self.txtvInput];
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
if ([textView.text length] > self.nNumberCount) {
textView.text = [textView.text substringToIndex:self.nNumberCount];
}
NSString *strText = textView.text;
if (strText.length < self.nNumberCount) {
[self.shapeCursor setHidden:NO];
CGFloat fOriginX = (294 - 45 * self.nNumberCount)/2;
CGRect frame = CGRectMake(fOriginX + 16.5 + 45 * [strText length], 57, 2, 26);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
[self.shapeCursor setPath:path.CGPath];
} else {
[self.shapeCursor setHidden:YES];
}
for (int i = 0; i < [self.arrBlackPoint count]; i++) {
[self.arrBlackPoint[i] setHidden:i >= strText.length];
}
}
@end
调用方法:
NumberCodeInputView *inputView = [[NumberCodeInputView alloc] initWithNumberCount:4 viewTitle:@"请输入密码" cancelTitle:@"取消" confirmTitle:@"确认" complete:^(NSString * _Nonnull strNumberCode) {
if ([strNumberCode isEqualToString:@"0000"]) {
[self.inputNumber removeFromSuperview];
} else {
NSLog(@"密码是4个0啊");
}
}];
[[UIApplication sharedApplication].keyWindow addSubview:inputView];
self.inputNumber= inputView;
实现效果: