上一篇简述了UITextField的属性及方法,本篇实际应用练习使用。
具体属性及方法可以参考上一篇UITextField简介:UITextField简介
首先看一下效果图:
实现了3位4位4位的手机账号格式,限制11位账号,验证是不是手机号码,UITextField属性和方法的运用等等。具体参考如下代码:
#import
@interface ViewController : UIViewController
@end
#import "ViewController.h"
@interface ViewController ()
{
NSString *previousTextFieldContent;
UITextRange *previousSelection;
}
@property (nonatomic, strong) UITextField *login;
@property (nonatomic, strong) UITextField *password;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//创建控件
[self creatControl];
}
- (void)creatControl
{
//lable
NSArray *array = @[@"手机账号: ", @"登录密码: "];
for (int i = 0; i < 2; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 100 + 50 * i, 80, 30)];
label.text = array[i];
[self.view addSubview:label];
}
//账号textField初始化
self.login = [[UITextField alloc] initWithFrame:CGRectMake(110, 100, 200, 30)];
//提醒文字
_login.placeholder = @"请输入手机号";
//键盘外观
_login.keyboardAppearance= UIKeyboardAppearanceDefault;
//键盘右下角按钮样式
_login.returnKeyType = UIReturnKeyNext;
//键盘右下角完成点击事件
[_login addTarget:self action:@selector(next) forControlEvents:UIControlEventEditingDidEndOnExit];
//textField变化时事件
[_login addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
//清除按钮
_login.clearButtonMode = UITextFieldViewModeWhileEditing;
//键盘样式
_login.keyboardType = UIKeyboardTypeNumberPad;
//设置代理
_login.delegate = self;
[self.view addSubview:_login];
//密码textField
self.password = [[UITextField alloc] initWithFrame:CGRectMake(110, 150, 200, 30)];
_password.placeholder = @"请输入密码";
_password.secureTextEntry = YES;
_password.returnKeyType = UIReturnKeyDone;
_password.clearButtonMode = UITextFieldViewModeWhileEditing;
[_password addTarget:self action:@selector(loginBtnOnClick) forControlEvents:UIControlEventEditingDidEndOnExit];
[self.view addSubview:_password];
//登陆button
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(220, 180, 60, 30)];
button.backgroundColor = [UIColor orangeColor];
[button setTitle:@"登陆" forState:UIControlStateNormal];
[button addTarget:self action:@selector(loginBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
//点击空白区域,隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//结束编辑
[self.view endEditing:YES];
}
- (void)next
{
//取消登录textField第一响应者
[_login resignFirstResponder];
//设置密码textField为第一响应者
[_password becomeFirstResponder];
}
- (void)textFieldEditingChanged:(UITextField *)textField
{
//限制手机账号长度(有两个空格)
if (textField.text.length > 13) {
textField.text = [textField.text substringToIndex:13];
}
NSUInteger targetCursorPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *preStr = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
//正在执行删除操作时为0,否则为1
char editFlag = 0;
if (currentStr.length <= preStr.length) {
editFlag = 0;
}
else {
editFlag = 1;
}
NSMutableString *tempStr = [NSMutableString new];
int spaceCount = 0;
if (currentStr.length < 3 && currentStr.length > -1) {
spaceCount = 0;
}else if (currentStr.length < 7 && currentStr.length > 2) {
spaceCount = 1;
}else if (currentStr.length < 12 && currentStr.length > 6) {
spaceCount = 2;
}
for (int i = 0; i < spaceCount; i++) {
if (i == 0) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(0, 3)], @" "];
}else if (i == 1) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(3, 4)], @" "];
}else if (i == 2) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
}
}
if (currentStr.length == 11) {
[tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
}
if (currentStr.length < 4) {
[tempStr appendString:[currentStr substringWithRange:NSMakeRange(currentStr.length - currentStr.length % 3, currentStr.length % 3)]];
}else if(currentStr.length > 3 && currentStr.length <12) {
NSString *str = [currentStr substringFromIndex:3];
[tempStr appendString:[str substringWithRange:NSMakeRange(str.length - str.length % 4, str.length % 4)]];
if (currentStr.length == 11) {
[tempStr deleteCharactersInRange:NSMakeRange(13, 1)];
}
}
textField.text = tempStr;
// 当前光标的偏移位置
NSUInteger curTargetCursorPosition = targetCursorPosition;
if (editFlag == 0) {
//删除
if (targetCursorPosition == 9 || targetCursorPosition == 4) {
curTargetCursorPosition = targetCursorPosition - 1;
}
}else {
//添加
if (currentStr.length == 8 || currentStr.length == 4) {
curTargetCursorPosition = targetCursorPosition + 1;
}
}
UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];
[textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition :targetPosition]];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
previousTextFieldContent = textField.text;
previousSelection = textField.selectedTextRange;
return YES;
}
- (void)loginBtnOnClick
{
//去空格
NSString *text = [_login.text stringByReplacingOccurrencesOfString:@" " withString:@""];
//验证长度
if (text.length < 11) {
NSLog(@"请输入正确的手机号");
return;
}
//验证是不是手机号码
if ([self isMobileNumber:text] == NO) {
NSLog(@"请输入正确的手机号");
return;
}
if (_password.text.length < 1) {
NSLog(@"请输入密码");
return;
}
NSLog(@"正在校验帐号密码...");
}
//验证手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
//正则表达式
NSString *mobile = @"^1\\d{10}$";
NSPredicate *regextestMobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobile];
if ([regextestMobile evaluateWithObject:mobileNum] == YES) {
return YES;
}else {
return NO;
}
}
@end
今天需求要用“-”代替“ ”,发现直接改有问题,重写了一下,效果图如下:
下面贴上核心代码:
@property (nonatomic, copy) NSString *preText;
#pragma mark - UITextFieldDelegate
- (void)textFieldEditingChanged:(UITextField *)textField
{
if (textField == _userName) {
//限制长度
if (textField.text.length > 13) {
textField.text = _preText;
return;
}
//光标位置
NSUInteger position = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
//是否正在添加
BOOL isAdd = textField.text.length > _preText.length ? YES : NO;
//去“-”后的文字
NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
//转临时可变字符串
NSMutableString *tempStr = [currentStr mutableCopy];
//计算拥有“-”的个数
int spaceCount = 0;
if (currentStr.length < 4 && currentStr.length > -1) {
spaceCount = 0;
}else if (currentStr.length < 8 && currentStr.length > 3) {
spaceCount = 1;
}else if (currentStr.length < 12 && currentStr.length > 7) {
spaceCount = 2;
}
//循环添加“-”
for (int i = 0; i < spaceCount; i++) {
if (i == 0) {
[tempStr insertString:@"-" atIndex:3];
}else if (i == 1) {
[tempStr insertString:@"-" atIndex:8];
}
}
//赋值回textField
textField.text = tempStr;
//计算光标的偏移位置
if (isAdd) {
if (currentStr.length == 4 || currentStr.length == 8) position++;
}else {
if (position == 4 || position == 9) position--;
}
//设置光标的偏移位置
UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:position];
[textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition:targetPosition]];
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == _userName) _preText = textField.text;
return YES;
}