//
// HanNumberTextField.h
// HanTTT
//
// Created by Han on 2020/9/3.
// Copyright © 2020 Han. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface HanNumberTextField : UITextField
@end
NS_ASSUME_NONNULL_END
//
// HanNumberTextField.m
// HanTTT
//
// Created by Han on 2020/9/3.
// Copyright © 2020 Han. All rights reserved.
//
#import "HanNumberTextField.h"
@interface HanNumberTextField()<UITextFieldDelegate>
@end
@implementation HanNumberTextField
- (instancetype)init
{
self = [super init];
if (self) {
self.delegate = self;
self.keyboardType = UIKeyboardTypeDecimalPad;
}
return self;
}
-(void)awakeFromNib{
[super awakeFromNib];
self.delegate = self;
self.keyboardType = UIKeyboardTypeDecimalPad;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL isHaveDian;
// 判断是否有小数点
if ([textField.text containsString:@"."]) {
isHaveDian = YES;
}else{
isHaveDian = NO;
}
if (string.length > 0) {
//当前输入的字符
unichar single = [string characterAtIndex:0];
// 不能输入.0-9以外的字符
if (!((single >= '0' && single <= '9') || single == '.'))
{
//SVHUD_HINT(@"您的输入格式不正确");
return NO;
}
// 只能有一个小数点
if (isHaveDian && single == '.') {
//SVHUD_HINT(@"最多只能输入一个小数点");
return NO;
}
// 如果第一位是.则前面加上0.
if ((textField.text.length == 0) && (single == '.')) {
textField.text = @"0";
}
// 如果第一位是0则后面必须输入点,否则不能输入。
if ([textField.text hasPrefix:@"0"]) {
if (textField.text.length > 1) {
NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
if (![secondStr isEqualToString:@"."]) return NO;
}else{
if (![string isEqualToString:@"."]) return NO;
}
}
// 小数点后最多能输入两位
if (isHaveDian) {
NSRange ran = [textField.text rangeOfString:@"."];
// 由于range.location是NSUInteger类型的,所以这里不能通过(range.location - ran.location)>2来判断
if (range.location > ran.location) {
if ([textField.text pathExtension].length > 1) {
return NO;
}
}
}
}
return YES;
}
@end
网友评论