IOS15实现经典登录页面,手机号带格式化功能
核心源码
#import "LJPhoneTextField.h"
// 设置RGB颜色
#define RGB(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
@implementation LJPhoneTextField
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.leftViewMode = UITextFieldViewModeAlways;
self.clearButtonMode = UITextFieldViewModeWhileEditing;
self.backgroundColor = [UIColor whiteColor];
self.textColor = RGB(51,51,51);
[self addTarget:self action:@selector(reformatAsPhoneNumber:) forControlEvents:UIControlEventEditingChanged];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self addTarget:self action:@selector(reformatAsPhoneNumber:) forControlEvents:UIControlEventEditingChanged];
}
return self;
}
-(void)reformatAsPhoneNumber:(UITextField *)textField {
/**
* 判断正确的光标位置
*/
NSUInteger targetCursorPostion = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
NSString *phoneNumberWithoutSpaces = [self removeNonDigits:textField.text andPreserveCursorPosition:&targetCursorPostion];
if([phoneNumberWithoutSpaces length]>11) {
/**
* 避免超过11位的输入
*/
[textField setText:_previousTextFieldContent];
textField.selectedTextRange = _previousSelection;
return;
}
NSString *phoneNumberWithSpaces = [self insertSpacesEveryFourDigitsIntoString:phoneNumberWithoutSpaces andPreserveCursorPosition:&targetCursorPostion];
textField.text = phoneNumberWithSpaces;
UITextPosition *targetPostion = [textField positionFromPosition:textField.beginningOfDocument offset:targetCursorPostion];
[textField setSelectedTextRange:[textField textRangeFromPosition:targetPostion toPosition:targetPostion]];
}
/**
* 除去非数字字符,确定光标正确位置
*
* @param string 当前的string
* @param cursorPosition 光标位置
*
* @return 处理过后的string
*/
- (NSString *)removeNonDigits:(NSString *)string andPreserveCursorPosition:(NSUInteger *)cursorPosition {
NSUInteger originalCursorPosition =*cursorPosition;
NSMutableString *digitsOnlyString = [NSMutableString new];
for (NSUInteger i=0; i0)
{
if(i==3 || i==7) {
[stringWithAddedSpaces appendString:@" "];
if(i1)
{
return NO;
}
}
return YES;
}
@end
开源地址
https://gitee.com/johnson__save_admin/ljphone-text-field