仿写一款比较流行的短信验证页面,整理出下面一段非常有意思的代码.
虽然只是一个简单的页面,反复调整自认为比较OK.当然实现办法和思路不唯一,希望有兴趣的小伙伴一起品评.
用了一个 textField 和四个 label 控件
用了 textfield 的一个代理方法
代码只有一个系统代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@""]){// 判断删除操作
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",textField.text);
NSLog(@"%@",string);
if ([string isEqualToString:@""]){// 判断删除操作
if (textField.text. length == 0)_message1.text = string;
if (textField.text.length == 1)_message2.text = string;
if (textField.text.length == 2)_message3.text = string;
if (textField.text.length == 3)_message4.text = string;
}else {
if (textField.text.length == 1)_message1.text = string;
if (textField.text.length == 2)_message2.text = string;
if (textField.text.length == 3)_message3.text = string;
if (textField.text.length == 4)_message4.text = string;}});
NSLog(@"%@",textField.text);
NSLog(@"%@",string);
return 1;
}else {if (textField.text.length == 4)return 0;}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if ([string isEqualToString:@""]){// 判断删除操作
if (textField.text.length == 0)_message1.text = string;
if (textField.text.length == 1)_message2.text = string;
if (textField.text.length == 2)_message3.text = string;
if (textField.text.length == 3)_message4.text = string;
}else {
if (textField.text.length == 1)_message1.text = string;
if (textField.text.length == 2)_message2.text = string;
if (textField.text.length == 3)_message3.text = string;
if (textField.text.length == 4)_message4.text = string;
}
});
if ([string isEqualToString:@""]){// 判断删除操作
return 1;
}else {
if (textField.text.length == 4)return 0;
}
return 1;
}
属性
@interface MKReginsterMessageController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *messageTextField;
@property (weak, nonatomic) IBOutlet UILabel *message1;
@property (weak, nonatomic) IBOutlet UILabel *message2;
@property (weak, nonatomic) IBOutlet UILabel *message3;
@property (weak, nonatomic) IBOutlet UILabel *message4;
@end
小操作
textfield 的 tintcolor 设为 clear
textfield 的 textcolor 设为 clear
最后只要验证 textfield.text 文本就可以了.