iOS之自定义密码框


#import "UIKit/UIKit.h"

@class LYSurePWVC;

@protocol LYSurePWVCdelegate<NSObject>

-(void)LYSurePWVC:(LYSurePWVC*)LYSurePWVC isPWCorrect:(NSString *)isPWCorrect;

@end

@interface LYSurePWVC : UIView

@property(nonatomic,copy)NSString *title;

@property(nonatomic,assign)id<LYSurePWVCdelegate>delegate;

@end

**************


#import "LYSurePWVC.h"

#import "LYMyRequesthttp.h"

#import "Header.h"

#import "Masonry.h"

#import <MBProgressHUD.h>

#import "LYCommonMBprogresshud.h"

#define kDotSize CGSizeMake (10, 10) //密码点的大小

#define kDotCount 6  //密码个数

#define K_Field_Height (WIDTH==320?30:45//每一个输入框的高度

#define Screen_Width [UIScreen mainScreen].bounds.size.width

@interface LYSurePWVC ()

<UITextFieldDelegate>


@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) NSMutableArray *dotArray; //用于存放黑色的点点

@end


@implementation LYSurePWVC

-(instancetype)initWithFrame:(CGRect)frame{

    if(self=[super initWithFrame:frame]){

        self.backgroundColor=[UIColor colorWithHexString:@"#f6f6f6" alpha:1];

        self.title=@"输入支付密码";

//上部分的遮罩

        UIView *coverview=[[UIView alloc]initWithFrame:CGRectMake(0, -HEIGHT/3, WIDTH, HEIGHT/3)];

        coverview.backgroundColor=[UIColor colorWithWhite:0.5 alpha:0.6];

        [self addSubview:coverview];


        [self tipLabel];//提示语

        [self addSubview:self.textField];

        //页面出现时让键盘弹出

        [self.textField becomeFirstResponder];

        [self initPwdTextField];

            [self forgetPayPassword];//添加忘记支付密码按钮

        [self topLeftBtn];//

    }

    return self;

}

//最上方左箭头和提示

-(void)topLeftBtn{

    NSString *str=@"请输入支付密码";

    // 给 显示的文本一个区域

    CGSize contentMaxSizes = CGSizeMake(MAXFLOAT,30);

    // NSFontAttributeName 字体的大小

    NSDictionary *attributesDicts = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};

    //计算文本实际宽高的时候, 计算的字体大小要和label中设置的字体大小保持一致

    // 根据限定的条件, 来计算text 真实的宽高

    CGSize contentRealSizes =  [str boundingRectWithSize:contentMaxSizes options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDicts context:nil].size;

    UIButton *topleftBtn=[[UIButton alloc]initWithFrame:CGRectMake(0,0, WIDTH, 30)];

    [topleftBtn setImage:[UIImage imageNamed:@"backgray"] forState:UIControlStateNormal];

    [topleftBtn setTitle:str forState:UIControlStateNormal];

    topleftBtn.titleLabel.font=[UIFont systemFontOfSize:15];

    topleftBtn.imageEdgeInsets=UIEdgeInsetsMake(0,-contentRealSizes.width/2-20, 0,WIDTH/2-contentRealSizes.width/2);

    [topleftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [self addSubview:topleftBtn];

    [topleftBtn addTarget:self action:@selector(topleftBtn:) forControlEvents:UIControlEventTouchUpInside];

    UIView *linev=[[UIView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, 2)];

    linev.backgroundColor=[UIColor colorWithHexString:@"#eeeeee" alpha:1];

    [self addSubview:linev];

}

//消失当前view

-(void)topleftBtn:(UIButton *)sender{

    sender.enabled=NO;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        sender.enabled=YES;

    });

    if([self.delegate respondsToSelector:@selector(LYSurePWVC:isPWCorrect:)]){

                [self.delegate LYSurePWVC:self isPWCorrect:@"2"];

            }

}

//提示输入密码

-(void)tipLabel{

    UILabel *tipLabel=[[UILabel alloc]initWithFrame:CGRectMake(16, 35, WIDTH, 20)];

    tipLabel.text=@"请输入支付密码";

    tipLabel.font=[UIFont systemFontOfSize:14];

    tipLabel.textColor=[UIColor colorWithWhite:0.7 alpha:0.7];

    [self addSubview:tipLabel];

}

//忘记支付密码按钮

-(void)forgetPayPassword{

    UIButton *fogetpassBtn;

    if(WIDTH==320){

        fogetpassBtn=[[UIButton alloc]initWithFrame:CGRectMake(WIDTH-120, 90, 120, 30)];

    }else {

       fogetpassBtn =[[UIButton alloc]initWithFrame:CGRectMake(WIDTH-120, 120, 120, 30)];

    }

    [fogetpassBtn setTitle:@"忘记支付密码?" forState:UIControlStateNormal];

    [fogetpassBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

    fogetpassBtn.titleLabel.font=[UIFont systemFontOfSize:14];

    [fogetpassBtn addTarget:self action:@selector(forgetpayPassBtnClick) forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:fogetpassBtn];

}

-(void)forgetpayPassBtnClick{

    

    if([self.delegate respondsToSelector:@selector(LYSurePWVC:isPWCorrect:)]){

        [self.delegate LYSurePWVC:self isPWCorrect:@"3"];

    }

}


- (void)initPwdTextField

{

    //每个密码输入框的宽度

    CGFloat width = (Screen_Width - 32) / kDotCount;

    

    //生成分割线

    for (int i = 0; i < kDotCount - 1; i++) {

        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.textField.frame) + (i + 1) * width, CGRectGetMinY(self.textField.frame), 1, K_Field_Height)];


        lineView.backgroundColor = [UIColor grayColor];

        [self addSubview:lineView];

    }

    

    self.dotArray = [[NSMutableArray alloc] init];

    //生成中间的点

    for (int i = 0; i < kDotCount; i++) {

        UIView *dotView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.textField.frame) + (width - kDotCount) / 2 + i * width, CGRectGetMinY(self.textField.frame) + (K_Field_Height - kDotSize.height) / 2, kDotSize.width, kDotSize.height)];


        dotView.backgroundColor = [UIColor blackColor];

        dotView.layer.cornerRadius = kDotSize.width / 2.0f;

        dotView.clipsToBounds = YES;

        dotView.hidden = YES; //先隐藏

        [self addSubview:dotView];

        //把创建的黑色点加入到数组中

        [self.dotArray addObject:dotView];

    }

}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    NSLog(@"变化%@", string);

    if([string isEqualToString:@"\n"]) {

        //按回车关闭键盘

        [textField resignFirstResponder];

        return NO;

    } else if(string.length == 0) {

        

        //判断是不是删除键

        return YES;

    }

    else if(textField.text.length >= kDotCount) {

        //输入的字符个数大于6,则无法继续输入,返回NO表示禁止输入

        NSLog(@"输入的字符个数大于6,忽略输入");

        return NO;

    } else {

        return YES;

    }

}


/**

 *  清除密码

 */

//- (void)clearUpPassword

//{

//    self.textField.text = @"";

//    [self textFieldDidChange:self.textField];

//}



/**

 *  重置显示的点

 */

- (void)textFieldDidChange:(UITextField *)textField

{

    NSLog(@"%@", textField.text);

    //刚开始先全部隐藏

    for (UIView *dotView in self.dotArray) {

        dotView.hidden = YES;

    }

    //有几个字符,显示几个点

    for (int i = 0; i < textField.text.length; i++) {

        ((UIView *)[self.dotArray objectAtIndex:i]).hidden = NO;

    }

    

    if (textField.text.length == kDotCount) {

        

        NSLog(@"输入完毕");

        //*********验证支付密码;

        NSString  *url=[TESTBASEURL stringByAppendingString:@"api/user/verifyPwd"];

        NSString *psdStr=self.textField.text;

        

        NSDictionary *params=@{@"password":psdStr};

        [LYMyRequesthttp postVerifyZhifupasswordrequestWithUrl:url params:params successBlock:^(NSURLSessionDataTask *task, id responseObject) {

            if(responseObject){

                if([responseObject integerValue]==-1){

                    [[LYCommonMBprogresshud sharedManager]showProgresshudTextWith:self title:@"密码不正确" detailtitle:nil isOnDismissbg:NO hideAfterdelay:YES];

                    

                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                        [MBProgressHUD hideAllHUDsForView:self animated:YES];

                        if([self.delegate respondsToSelector:@selector(LYSurePWVC:isPWCorrect:)]){

                            [self.delegate LYSurePWVC:self isPWCorrect:@"0"];

                        }

                    });

                    

                }else if([responseObject integerValue]==1){//验证密码成功

                    

                    if([self.delegate respondsToSelector:@selector(LYSurePWVC:isPWCorrect:)]){

                        [self.delegate LYSurePWVC:self isPWCorrect:@"1"];

                    }

                    

                }

            }

            

        } failureBlock:^(NSURLSessionDataTask *task, NSError *error) {

            [[LYCommonMBprogresshud sharedManager]showProgresshudTextWith:self title:@"密码验证失败" detailtitle:nil isOnDismissbg:NO hideAfterdelay:YES];

            

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                [[LYCommonMBprogresshud sharedManager]dimisAnimalProgressWith:self];

                if([self.delegate respondsToSelector:@selector(LYSurePWVC:isPWCorrect:)]){

                     [self.delegate LYSurePWVC:self isPWCorrect:@"0"];

                }

            });

            

        }];

        

    }

}



#pragma mark - init


- (UITextField *)textField

{

    if (!_textField) {

        _textField = [[UITextField alloc] initWithFrame:CGRectMake(16, 60, Screen_Width - 32, K_Field_Height)];


        _textField.backgroundColor = [UIColor whiteColor];

        //输入的文字颜色为白色

        _textField.textColor = [UIColor whiteColor];

        //输入框光标的颜色为白色

        _textField.tintColor = [UIColor whiteColor];

        _textField.delegate = self;

        _textField.autocapitalizationType = UITextAutocapitalizationTypeNone;

        _textField.keyboardType = UIKeyboardTypeNumberPad;

        _textField.layer.borderColor = [[UIColor grayColor] CGColor];

        _textField.layer.borderWidth = 1;

        [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];//监听

        _textField.inputAccessoryView = [UIView new];//去掉右侧确定按钮


    }

    return _textField;

}

点解完成按钮时从父View移除

//-(void)textFieldDidEndEditing:(UITextField *)textField

//{

//    if([self.delegate respondsToSelector:@selector(LYSurePWVC:isPWCorrect:)]){

//        [self.delegate LYSurePWVC:self isPWCorrect:@"2"];

//    }

//    NSLog(@"dd");

//

//}

@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值