密码框 PasswordTextView 笔记

.h

@interface PasswordTextView : UIView

/**

the password is user inputed

*/

@property (nonatomic, copy) void(^passwordDidChangeBlock)(NSString *password);

/**

set element count, default is 4, remove all elements and creat new elemets when it was set

*/

@property (nonatomic, assign) NSInteger elementCount;

/**

set element color, default is balck color

*/

@property (nonatomic, strong) UIColor *elementBorderColor;

/**

set element margein, default is 4 point

*/

@property (nonatomic, assign) CGFloat elementMargin;

/**

auto hide the keyboard when input password was completed, default is YES

*/

@property (nonatomic, assign) BOOL autoHideKeyboard;

/**

set element border width, default's 1 point

*/

@property (nonatomic, assign) CGFloat elementBorderWidth;

/**

clear all password

*/

- (void)clearPassword;

- (void)showKeyboard;

- (void)hideKeyboard;



.m

@interface TPPasswordTextView ()

@property(nonatomic, weak) UITextField *textField;

@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation PasswordTextView

#pragma mark - lazy

- (NSMutableArray *)dataSource {

    if (_dataSource == nil) {

        _dataSource = [NSMutableArray array];

    }

    return _dataSource;

}


#pragma mark - initialization

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        UITextField *textField = [[UITextField alloc] initWithFrame:self.bounds];

        textField.hidden = YES;

        textField.keyboardType = UIKeyboardTypeNumberPad;

        [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];

        //使文本框在界面打开时就获取焦点,并弹出输入键盘

        [textField becomeFirstResponder];

        //使文本框失去焦点,并收回键盘

        //[textField resignFirstResponder];

        [self addSubview:textField];

        self.textField = textField;

        self.autoHideKeyboard = YES;

        self.elementBorderColor = [UIColor blackColor];

        self.backgroundColor = [UIColor whiteColor];

        self.elementBorderWidth = 1;

    }

    return self;

}

- (void)setElementCount:(NSInteger)elementCount {

    _elementCount = elementCount;

    if (elementCount <= 0) {

        return;

    }


    if (self.dataSource.count > 0) {

        [self.dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            [NSObject cancelPreviousPerformRequestsWithTarget:obj selector:@selector(removeFromSuperview) object:nil];

        }];


        [self.dataSource makeObjectsPerformSelector:@selector(removeFromSuperview)];


        [self.dataSource removeAllObjects];

    }


    for (int i = 0; i < self.elementCount; i++)

    {

        UITextField *pwdTextField = [[UITextField alloc] init];

        pwdTextField.enabled = NO;

        pwdTextField.textAlignment = NSTextAlignmentCenter;//居中

        pwdTextField.secureTextEntry = YES;//设置密码模式

        pwdTextField.userInteractionEnabled = NO;

        [self insertSubview:pwdTextField belowSubview:self.textField];

        [self.dataSource addObject:pwdTextField];

    }

}

- (void)setElementMargin:(CGFloat)elementMargin {

    _elementMargin = elementMargin;

    [self setNeedsLayout];

    [self setNeedsDisplay];

}

#pragma mark - publick method

- (void)clearPassword {

    self.textField.text = nil;

    [self textChange:self.textField];

}

- (void)showKeyboard {

    [self.textField becomeFirstResponder];

}

- (void)hideKeyboard {

    [self.textField resignFirstResponder];

}

#pragma mark - 文本框内容改变

- (void)textChange:(UITextField *)textField {

    NSString *password = textField.text;

    if (password.length > self.elementCount) {

        return;

    }


    for (int i = 0; i < self.dataSource.count; i++)

    {

        UITextField *pwdTextField= [self.dataSource objectAtIndex:i];

        if (i < password.length) {

            NSString *pwd = [password substringWithRange:NSMakeRange(i, 1)];

            pwdTextField.text = pwd;

        } else {

            pwdTextField.text = nil;

        }


    }


    if (password.length == self.dataSource.count)

    {

        if (self.autoHideKeyboard) {

            [self hideKeyboard];//隐藏键盘

        }

    }


    !self.passwordDidChangeBlock ? : self.passwordDidChangeBlock(textField.text);

}


- (void)layoutSubviews {

 [super layoutSubviews]; 

 CGFloat x = 0; 

 CGFloat y = 0; 

 CGFloat w = (self.bounds.size.width - (self.elementCount - 1) * self.elementMargin) / self.elementCount; 

 CGFloat h = self.bounds.size.height;

 for (NSUInteger i = 0; i < self.dataSource.count; i++) { 

 UITextField *pwdTextField = [self.dataSource objectAtIndex:i]; 

 x = i * (w + self.elementMargin); 

 pwdTextField.frame = CGRectMake(x, y, w, h); 

 }}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self showKeyboard];

}

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

    [super drawRect:rect];

    // Drawing code


    CGContextRef context = UIGraphicsGetCurrentContext();

    [self.backgroundColor set];

    CGContextFillRect(context, rect);


    CGContextSetLineCap(context, kCGLineCapSquare);


    CGContextSetLineWidth(context, self.elementBorderWidth);


    CGContextSetStrokeColorWithColor(context, self.elementBorderColor.CGColor);

    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);


    CGContextBeginPath(context);

    if (self.elementMargin != 0) {

        for (UITextField *textField in self.dataSource) {

            CGRect rect = CGRectInset(textField.frame, self.elementBorderWidth, self.elementBorderWidth);

            CGFloat left = rect.origin.x;

            CGFloat right = rect.origin.x + rect.size.width;

            CGFloat top = rect.origin.y;

            CGFloat bottom = rect.origin.y + rect.size.height;

            CGContextMoveToPoint(context, left, top);

            CGContextAddLineToPoint(context, right, top);

            CGContextAddLineToPoint(context, right, bottom);

            CGContextAddLineToPoint(context, left, bottom);

            CGContextClosePath(context);

        }

    }else {

        CGPoint leftTopPoint, rightTopPoint, leftBottomPoint, rightBottomPoint;

        for (NSUInteger i = 0; i < self.dataSource.count; i++) {

            UITextField *textField = [self.dataSource objectAtIndex:i];

            CGRect rect = CGRectInset(textField.frame, self.elementBorderWidth, self.elementBorderWidth);

            CGFloat left = rect.origin.x;

            CGFloat right = rect.origin.x + rect.size.width;

            CGFloat top = rect.origin.y;

            CGFloat bottom = rect.origin.y + rect.size.height;


            CGContextMoveToPoint(context, left, top);

            CGContextAddLineToPoint(context, left, bottom);

            CGContextClosePath(context);

            if (self.dataSource.count - 1 == i) {

                CGContextMoveToPoint(context, right, top);

                CGContextAddLineToPoint(context, right, bottom);

                CGContextClosePath(context);

                rightTopPoint = CGPointMake(right, top);

                rightBottomPoint = CGPointMake(right, bottom);

            }else if (0 == i) {

                leftTopPoint = CGPointMake(left, top);

                leftBottomPoint = CGPointMake(left, bottom);

            }

        }


        CGContextMoveToPoint(context, leftTopPoint.x, leftTopPoint.y);

        CGContextAddLineToPoint(context, rightTopPoint.x, rightTopPoint.y);

        CGContextClosePath(context);


        CGContextMoveToPoint(context, leftBottomPoint.x, leftBottomPoint.y);

        CGContextAddLineToPoint(context, rightBottomPoint.x, rightBottomPoint.y);

        CGContextClosePath(context);

    }


    CGContextStrokePath(context);

}


-------------------

使用


CGPoint center = self.view.center;

    TPPasswordTextView *view1 = [[TPPasswordTextView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];

    view1.elementCount = 5;

    view1.center = CGPointMake(center.x, 50);

    [self.view addSubview:view1];

    view1.passwordDidChangeBlock = ^(NSString *password) {

        NSLog(@"%@",password);

    };


    TPPasswordTextView *view2 = [[TPPasswordTextView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];

    view2.elementCount = 5;

    view2.center = CGPointMake(center.x, 100);

    view2.elementBorderColor = [UIColor redColor];

    [self.view addSubview:view2];

    view2.passwordDidChangeBlock = ^(NSString *password) {

        NSLog(@"%@",password);

    };


    TPPasswordTextView *view3 = [[TPPasswordTextView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];

    view3.elementCount = 8;

    view3.center = CGPointMake(center.x, 150);

    view3.elementBorderColor = [UIColor cyanColor];

    view3.elementMargin = 5;

    [self.view addSubview:view3];

    view3.passwordDidChangeBlock = ^(NSString *password) {

        NSLog(@"%@",password);

    };



    TPPasswordTextView *view4 = [[TPPasswordTextView alloc] initWithFrame:CGRectMake(0, 0, 288, 44)];

    view4.elementCount = 6;

    view4.center = CGPointMake(center.x, 200);

    view4.elementBorderColor = [UIColor grayColor];

    view4.elementMargin = 5;

    [self.view addSubview:view4];

    view3.passwordDidChangeBlock = ^(NSString *password) {

        NSLog(@"%@",password);

    };



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,738评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,377评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,774评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,032评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,015评论 5 361
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,239评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,724评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,374评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,508评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,410评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,457评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,132评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,733评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,804评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,022评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,515评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,116评论 2 341

推荐阅读更多精彩内容

  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 2,467评论 1 14
  • #define kBlackColor [UIColor blackColor] //.h //划线 + (voi...
    CHADHEA阅读 777评论 0 1
  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,114评论 1 6
  • 一 我永远得不到的你 你说可笑吗? 这种阴暗背德的感情,不被所有人接受,没人站在你这边鼓励你说什么加油啊再努力一点...
    郭汐汐阅读 16,213评论 8 58
  • 1.法律与良心 幽默:在柏林墙推倒的前两年,东德一个名叫亨里奇的守墙卫兵,开枪射杀了攀爬柏林墙希图逃向西德的青年克...
    小好阅读 1,709评论 0 3