iOS 自定義數字密碼彈窗

說到實現一個彈窗,我們很多人第一反應就會想到使用系統的 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;

實現效果:

自定義數字密碼彈窗
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,412評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,514評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,373評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,975評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,743評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,199評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,262評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,414評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,951評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,780評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,527評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,218評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,649評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,889評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,673評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,967評論 2 374

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,151評論 4 61
  • 歡迎繼續學習關于菲伯爾教學法的內容。 菲伯爾系列教程能夠捕捉孩子的童真,在充滿樂趣的歌曲、節奏游戲和技術活動中發展...
    MissHanStudio閱讀 3,202評論 0 4
  • 幼兒園的征文終于交上去了,心里松了一口氣。以前,從未參加過這樣的活動,但是近期學了那么多網絡課,也嘗試了成為輸出者...
    56東南西閱讀 140評論 2 0
  • Foodie是一款專業為美食加濾鏡的APP(親測濾鏡效果棒棒噠、小清新、簡單極致、加上濾鏡后的食物更有食欲)。 版...
    SunshineGirLL閱讀 629評論 0 0