ios - tableview 上的 textfield.text 显示值 null

标签 ios

我使用下面的代码将文本字段添加到每个 tableview 单元格,

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSInteger row=[indexPath row];
    static NSString *SimpleTableIdentifier1 = @"CellTableIdentifier";
    //if I change the code to [NSString *SimpleTableIdentifier1 =NSString stringWithFormat:@"CellTableIdentifier%d",row]; everything is fine         


    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier1 ];

    if  (cell == nil){

        CGRect cellframe=CGRectMake(0, 0, 200, 60);
        cell=[[[UITableViewCell alloc] initWithFrame: cellframe  reuseIdentifier:SimpleTableIdentifier1] autorelease];
        UITextField * textfieldCell =[[UITextField alloc]init];
        textfieldCell.frame = CGRectMake(100.0f,20.0f,60.0f,26.0f) ;
        [textfieldCell setDelegate:self];
        [textfieldCell setTag:40000+row];//add row value here for later use, 
        [cell.contentView addSubview:textfieldCell];
        [textfieldCell release];

    }
    UITextField *textfieldCell ;

    textfieldCell =(UITextField*)[cell.contentView viewWithTag:40000+row];
    textfieldCell.text=[ NSMutableString  stringWithString:@"aaa1"];
    DebugLog(@"---------%@",textfieldCell.text);

    return cell;


}

textfieldCell.text 有时会显示 null 而不是我对 'aaa1' 的期望值

这意味着代码行位于:

textfieldCell =(UITextField*)[cell.contentView viewWithTag:40000+row];

有时返回nil,尝试修复这个困惑的结果但失败

欢迎您的评论

最佳答案

这个dequeueReusableCellWithIdentifier

 UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier1 ];

返回一个非零单元格 Docs

This method dequeues an existing cell if one is available or creates a new one using the class or nib file you previously registered. If no cell is available for reuse and you did not register a class or nib file, this method returns nil

可能有一个带有不同标签的 textField 导致 nil

 UITextField *textfieldCell ;

因为这两行

// here rhs may be nil
textfieldCell =(UITextField*)[cell.contentView viewWithTag:40000+row];
textfieldCell.text=[ NSMutableString  stringWithString:@"aaa1"];

对 nil textfield 没有影响,而且令人震惊的是你仍然在这里使用 MRC(手动引用计数)

[textfieldCell release];

请更新到 ARC(自动引用计数),这将消除您对内存管理问题的担忧

关于ios - tableview 上的 textfield.text 显示值 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291267/

相关文章:

ios - iOS 8 中带有 native 预测的自定义键盘

objective-c - 用于呈现多个模态的 NSNotificationCenter?

ios - UIApplicationWillEnterForegroundNotification与application:openURL:sourceApplication:annotation:

ios - 无法使用mockURLSession调用非函数类型 'URLSession'错误的值

ios - UIView.transitionWithView 破坏加载器的布局

ios - detailtext标签未显示

ios - 如何突出显示 UITextField 内的部分文本?

ios - 从文档目录IOS中的文件夹保存和检索文件

ios - 圆形按钮增大尺寸后变成圆角矩形

ios - Swift iOS 无法识别 GCM 库导入?