美观简洁的数字键盘,支持小数、整数、负数、文本长度的控制
效果图
EBNumberTextField.gifgithub地址:https://github.com/woheduole/EBCustomControls
调用示例
EBNumberTextField *textField = [[EBNumberTextField alloc] initWithFrame:CGRectMake(115, y, 150, 30)];
// 键盘类型
textField.numberKeyboardType = EBNumberKeyboardTypeInteger;
// 文本长度
textField.maxLength = 5;
[self.view addSubview:textField];
实现步骤
- 定义一个键盘视图EBNumberKeyboardView在里面写好布局,代码没什么难点,这里就不贴出布局代码了,代理里面我定义了四个回调方法。
@protocol EBNumberKeyboardViewDelegate <NSObject>
@optional
// 输入数字、小数点、负号
- (void)numberKeyboardViewEditing:(EBNumberKeyboardView *)keyboardView text:(NSString*)text;
// 点击完成输入
- (void)numberKeyboardViewEndEditing:(EBNumberKeyboardView *)keyboardView;
// 删除字符
- (void)numberKeyboardViewDeleteText:(EBNumberKeyboardView *)keyboardView;
// 清空文本
- (void)numberKeyboardViewClearText:(EBNumberKeyboardView *)keyboardView;
@end
- 定义一个继承自UITextField的视图EBNumberTextField,在里面指定self.inputView = "定义的键盘视图"。
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_maxLength = 0;
EBNumberKeyboardView *numberKeyboardView = [[EBNumberKeyboardView alloc] initWithKeyboardType:EBNumberKeyboardTypeDecimal];
numberKeyboardView.delegate = self;
self.inputView = numberKeyboardView;
/*
1.当使用第三方键盘管理类IQKeyboardManager,禁用toolBar
2.如果没有用到第三方键盘管理可以不加这行代码
3.可以把[UIView new]替换成一个自定义的视图来实现IQKeyboardManager的toolbar功能
*/
self.inputAccessoryView = [UIView new];
_numberKeyboardView = numberKeyboardView;
}
return self;
}
#pragma mark - EBNumberKeyboardViewDelegate
// 输入数字、小数点、负号
- (void)numberKeyboardViewEditing:(EBNumberKeyboardView *)keyboardView text:(NSString*)text {
if ([text isEqualToString:kEBNumberKeyboardViewDotKey]) {
// 小数点不能在第一位并且只能有一个小数点
if (self.text.length == 0
|| [self.text rangeOfString:kEBNumberKeyboardViewDotKey].location != NSNotFound) {
return;
}
}else if([text isEqualToString:kEBNumberKeyboardViewMinusKey]) {
// 负号只能在第一位
if (self.text.length > 0) {
return;
}
}
NSString *fullText = [self.text stringByAppendingString:text];
if (_maxLength >0 && fullText.length > _maxLength) {
return;
}
[self insertText:text];
}
// 点击完成输入
- (void)numberKeyboardViewEndEditing:(EBNumberKeyboardView *)keyboardView {
[self resignFirstResponder];
}
// 删除字符
- (void)numberKeyboardViewDeleteText:(EBNumberKeyboardView *)keyboardView {
[self deleteBackward];
}
// 清空文本
- (void)numberKeyboardViewClearText:(EBNumberKeyboardView *)keyboardView {
self.text = @"";
}
注意:
调用[self insertText:text]插入输入文本,这样光标在哪,插入的代码就在哪。
通过[self deleteBackward]删除文本,会从光标那里开始往前删除。
网友评论