iOS開發(fā) UITableView中cell嵌套UITextField(UITextView)引起的復(fù)用問題

不喜歡說廢話,如果你選擇看這篇文章,那對tableView就有一定的了解,所以我也不多說了。在開發(fā)項目中遇到了一個問題,在自定義cell中添加了UITextField,可是在tableView來回滾動中,原來在UITextField中輸入的數(shù)據(jù)居然不見了,下面就來分享下自己是如何解決的。

整體思路:

找到textField的代理方法先監(jiān)聽他的數(shù)據(jù)變化,然后通過字典把變化的數(shù)據(jù)和cell的行數(shù)進(jìn)行綁定,因為cell復(fù)用他的每個cell的indexPah.row是不會變的,然后通過一個數(shù)組將字典里保存的key取出來每次重繪cell的時候進(jìn)行判斷,/如果字典中保存當(dāng)前的值,那么直接從字典里取出值然后賦給UITextField的text就完美解決啦。

代碼實現(xiàn):

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中監(jiān)聽textField變化的值,并通過字典把變化的值和cell的indexPath.row進(jìn)行一一對應(yīng)
- (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){
        
        //將發(fā)生改變的textField的內(nèi)容對應(yīng)cell的行
        [self.dataDict setValue:text forKey:FStr(@"%ld",indexPath.row)];
    };
    
      // 取出存儲所有textFileld改變對應(yīng)的行
    NSArray *indexArr  = [self.dataDict allKeys];
    if ([indexArr containsObject:FStr(@"%ld",indexPath.row)]) {
   // 如果字典中保存當(dāng)前的值,那么直接從字典里取出值然后賦給UITextField的text
        cell.tfUrlBlock.text = [self.dataDict objectForKey:FStr(@"%ld",indexPath.row)];
        } else {
            cell.tfUrlBlock.text =nil'
        return cell;
    }

免費獲取IT界4T開發(fā)資料

第一步:

微信關(guān)注:


微信公眾號
第二步:

回復(fù)關(guān)鍵字:我要資料

獲取資料
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容