特性
- 占位文字上浮
- 输入内容错误时,下方显示提示信息
- 输入框右下角显示字数限制
- 显示历史输入记录列表,方便用户输入
- 线型边框,输入时/错误时改变线条颜色
预览
ezgif.com-resize.gif
使用
YJJTextField *textField = [YJJTextField yjj_textField];
textField.frame = CGRectMake(0, 60, self.view.frame.size.width, 80);
textField.maxLength = 11;
textField.errorStr = @"字数长度不得超过11位";
textField.placeholder = @"请输入用户名";
textField.historyContentKey = @"userName";
[self.view addSubview:textField];
如何实现历史记录列表
- 用户输入完成之后进行保存,此处用
NSUserDefaults
进行存储
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *originalDic = [defaults objectForKey:@"historyContent"];
if (originalDic == nil) { // 如果系统中没有记录
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
for (YJJTextField *textField in self.textFieldArr) {
// 用数组存放输入的内容,并作为保存字典的Value,Key为用户在创建时自己指定
NSArray *array = [NSArray arrayWithObject:textField.textField.text];
[dic setObject:array forKey:textField.historyContentKey];
}
[defaults setObject:dic forKey:@"historyContent"];
}else{
__block NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:0];
for (YJJTextField *textField in self.textFieldArr) {
// 遍历所有TextField,取出当前文本框的Key和内容
NSString *currentKey = textField.historyContentKey;
NSString *currentText = textField.textField.text;
__block NSMutableArray *contentArray;
// 遍历已经存在的记录
[originalDic enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *obj, BOOL * _Nonnull stop) {
contentArray = [NSMutableArray arrayWithArray:obj];
if ([key isEqualToString:currentKey]) { // 如果当前Key和字典中的Key相同,则添加Value
[contentArray addObject:currentText];
// 去除重复的记录
NSSet *set = [NSSet setWithArray:contentArray];
contentArray = (NSMutableArray *)set.allObjects;
[newDic setObject:contentArray forKey:currentKey];
*stop = YES;
}
}];
}
[defaults setObject:newDic forKey:@"historyContent"];
}
- 显示历史记录列表
- 在用户开始编辑时,去
NSUserDefaults
中读取数据
self.historyContentArr = nil;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dic = [defaults objectForKey:@"historyContent"];
for (NSString *string in dic.allKeys) {
if ([string isEqualToString:key]) {
self.historyContentArr = dic[string];
break;
}
}
2. 如果数据不为空,则创建`UITableView`,实现数据源和代理方法,并将其加载到`keyWindow`上
self.window = [UIApplication sharedApplication].keyWindow;
self.window.backgroundColor = [UIColor clearColor];
[self.window addSubview:self.tableView];
self.tableView.frame = CGRectMake(margin, y, self.frame.size.width-margin*2, tableViewH);
[UIView animateWithDuration:animateDuration animations:^{
self.tableView.alpha = 1.0;
}];
- 取消历史记录列表
[UIView animateWithDuration:animateDuration animations:^{
self.tableView.alpha = 0.0;
} completion:^(BOOL finished) {
[self.tableView removeFromSuperview];
self.window = nil;
}];
源码
github链接 https://github.com/yjjwxy2/YJJTextField
网友评论