不喜歡說廢話,如果你選擇看這篇文章,那對tableView就有一定的了解,所以我也不多說了。在開發項目中遇到了一個問題,在自定義cell中添加了UITextField,可是在tableView來回滾動中,原來在UITextField中輸入的數據居然不見了,下面就來分享下自己是如何解決的。
整體思路:
找到textField的代理方法先監聽他的數據變化,然后通過字典把變化的數據和cell的行數進行綁定,因為cell復用他的每個cell的indexPah.row是不會變的,然后通過一個數組將字典里保存的key取出來每次重繪cell的時候進行判斷,/如果字典中保存當前的值,那么直接從字典里取出值然后賦給UITextField的text就完美解決啦。
代碼實現:
1.通過UITextField的代理方法
在.h文件中
#import "HWBaseCell.h"
@interface HWTitleTextFieldCell : HWBaseCell
@property (weak, nonatomic) IBOutlet UITextField *tfUrlBlock;
@property (nonatomic, copy)void (^saveData)(NSString *text);
@end
在.m文件中
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (_saveData) {
_saveData([textField.text stringByReplacingCharactersInRange:range withString:string]);
}
return YES;
}
2.在TableViewController中監聽textField變化的值,并通過字典把變化的值和cell的indexPath.row進行一一對應
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *identifier = NSStringFromClass([HWTitleTextFieldCell class]);
HWTitleTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
Class cellClass = NSClassFromString(identifier);
cell = [[cellClass alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.saveData = ^(NSString *text){
//將發生改變的textField的內容對應cell的行
[self.dataDict setValue:text forKey:FStr(@"%ld",indexPath.row)];
};
// 取出存儲所有textFileld改變對應的行
NSArray *indexArr = [self.dataDict allKeys];
if ([indexArr containsObject:FStr(@"%ld",indexPath.row)]) {
// 如果字典中保存當前的值,那么直接從字典里取出值然后賦給UITextField的text
cell.tfUrlBlock.text = [self.dataDict objectForKey:FStr(@"%ld",indexPath.row)];
} else {
cell.tfUrlBlock.text =nil'
return cell;
}
免費獲取IT界4T開發資料
第一步:
微信關注:
微信公眾號
第二步:
回復關鍵字:我要資料
獲取資料