博客> 输入密码框的实现
输入密码框的实现
2017-09-24 05:17 评论:0 阅读:215 飞翔信念
输入密码框的实现

今天项目中用到了一个输入密码框功能,搜了一下,发现一个比较好用的,在原有基础上稍微做了一下改动,原理是自定义一个UIView的类,实现输入密码框 1. .h文件实现

#import <UIKit>

@interface PasswordTextView : UIView

@property (nonatomic, copy) void(^passwordBlock)(NSString *password);
@property (nonatomic, assign) NSUInteger elementCount;
@property (nonatomic, strong) UIColor *elementColor;
@property (nonatomic, assign) NSUInteger elementMargin;
@property (nonatomic,strong) UITextField *textField;
- (void)clearText;

@end

2. .m文件实现

#import "PasswordTextView.h"

@interface PasswordTextView ()
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation PasswordTextView

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray arrayWithCapacity:self.elementCount];
    }
    return _dataSource;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _textField = [[UITextField alloc] initWithFrame:self.bounds];
        _textField.hidden = YES;
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        [_textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
        [self addSubview:_textField];
    }
    return self;
}

//xib创建会走这个方法
- (id)initWithCoder:(NSCoder*)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // Initialization code
        _textField = [[UITextField alloc] initWithFrame:self.bounds];
        _textField.hidden = YES;
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        [_textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
        [self addSubview:_textField];
    }
    return self;
}

- (void)setElementCount:(NSUInteger)elementCount {
    _elementCount = elementCount;
    for (int i = 0; i < self xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed> self.elementCount) {
        return;
    }

    for (int i = 0; i < _dataSource.count; i++)
    {
        UITextField *pwdTextField= [_dataSource objectAtIndex:i];
        if (i < password xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed> *)touches withEvent:(UIEvent *)event {
    [self.textField becomeFirstResponder];
}

用的时候直接创建类对象就可以了,可以设置密码位数及输入框的颜色,xib拖拽的会走initwithcoder方法。

收藏
0
sina weixin mail 回到顶部