思路:设置一个textField隐藏,然后遍历输入的内容,展示在四个textField中,代码如下:
#import "DemoViewController.h"
@interface DemoViewController ()<UITextFieldDelegate>
{
UITextField *topTX;
NSMutableArray *dataSource;
}
@end
@implementation DemoViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"仿支付宝密码输入框";
dataSource = [[NSMutableArray alloc] initWithCapacity:10];
[self setUI];
}
- (void)setUI
{
topTX = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
topTX.hidden = YES;
topTX.keyboardType = UIKeyboardTypeNumberPad;
[topTX addTarget:self action:@selector(txchange:) forControlEvents:UIControlEventEditingChanged];
[self.view addSubview:topTX];
//进入界面,topTX成为第一响应
[topTX becomeFirstResponder];
for (int i = 0; i < 4; i++)
{
UITextField *pwdLabel = [[UITextField alloc] initWithFrame:CGRectMake(90+i*40, 100, 30, 30)];
pwdLabel.layer.borderColor = [UIColor redColor].CGColor;
pwdLabel.enabled = NO;
pwdLabel.textAlignment = NSTextAlignmentCenter;//居中
pwdLabel.secureTextEntry = YES;//设置密码模式
pwdLabel.layer.borderWidth = 1;
[self.view addSubview:pwdLabel];
[dataSource addObject:pwdLabel];
}
}
#pragma mark 文本框内容改变
- (void)txchange:(UITextField *)tx
{
NSString *password = tx.text;
if (password.length == dataSource.count)
{
[tx resignFirstResponder];//隐藏键盘
}
for (int i = 0; i < dataSource.count; i++)
{
UITextField *pwdtx = [dataSource objectAtIndex:i];
if (i < password.length)
{
NSString *pwd = [password substringWithRange:NSMakeRange(i, 1)];
pwdtx.text = pwd;
}
}
if (password.length == 4)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"输入的密码是" message:password delegate:nil cancelButtonTitle:@"完成" otherButtonTitles:nil, nil];
[alert show];
}
}
效果图如下:
为毛键盘没有显示出来,各位可以自己亲自试一试,思路来自于其他
简友 ,自己只是按照别人的逻辑再重现一遍,膜拜下。。