說到實現一個彈窗,我們很多人第一反應就會想到使用系統的 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
消失掉,這樣的交互是一種糟糕的體驗。
既然 UIAlertController
既不切合實際,布局又不美觀,那我們只好選擇自定義來實現了。我們看到現在市場上的密碼彈窗,看上去是一個個小的 UITextField
排起來的,但是如果是這樣的話,感覺有點太麻煩,后來在網上查了一下,發現有人將一個完全隱藏的 UITextView
做鍵盤輸入響應,用一排 UILabel
做已經輸入數字顯示,用一個閃爍的動畫作待輸入光標。
這是該作者的原文地址 iOS自定義驗證碼輸入框(4位或6位)
根據這個作者的文章結合項目的實際需要,做了一下適當的修改,封裝成了一個叫 NumberCodeInputView
的工具類,具體代碼如下:
在 NumberCodeInputView.h
頭文件的代碼:
#import <UIKit/UIKit.h>
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 () <UITextViewDelegate>
/**
數組數量
*/
@property (nonatomic, assign) NSInteger nNumberCount;
/**
字符串數組 0、彈窗標題 1、取消標題 2、確認標題
*/
@property (nonatomic, strong) NSArray<NSString *> *arrTitle;
/**
輸入視圖
*/
@property (nonatomic, weak) UITextView *txtvInput;
/**
輸入數字隱藏的黑點
*/
@property (nonatomic, strong) NSArray<UIView *> *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;
實現效果:
自定義數字密碼彈窗