ios 从 uitableViewCell 中的文本字段获取文本值

ios get text value from textfield in tableViewCell

在我的 ViewController 中,我创建了一个名为 UITextField *txtMyName; 的文本字段 之后,我将 textField 添加到 tableViewCell [cell addSubview:txtMyName];

我可以在我的 textField 中编辑文本,但是当我从 textField 中获取文本时 _strFullName = txtMyName.text;

但是,它得到的是空值。

如何解决这个问题!

***** 已编辑****

if (indexPath.row == 0) {
        [self setFrameTextField:cell];
        [self CustomTextField:cell :txtMyName];
        if ([[dict_infoFriend objectForKey:@"Fullname"] isEqualToString:@" "]) {
            txtMyName.placeholder = @"Name";
        }
        else{
            txtMyName.text = [dict_infoFriend objectForKey:@"Fullname"];
        }
        [cell addSubview:txtMyName];
    }
else if (indexPath.row == 1){
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            button.frame = CGRectMake(cell.frame.size.width - 10, 0, 130, 40);
        }
        else{
            button.frame = CGRectMake(cell.frame.size.width / 2 - 65, 0, 130, 40);
        }
        [self CustomBTN:button];
        [button addTarget:self action:@selector(ClickDone) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:button];
    }

您还没有为您的文本字段分配内存,这就是为什么您可以编辑但无法检索它的原因。只需写 txtMyName = [[UITextfield alloc]init]; 你就可以像 txtMyName = [[UITextfield alloc]initWithFrame:CGRectMake(x,y,width,height)]; 一样将框架分配给文本字段 一旦你将内存分配给你的文本字段然后你将从文本字段中检索文本

由于您已将文本字段添加到 table 单元格中,因此您必须先获取单元格,然后使用文本字段的标签才能获取文本。

这样试试,

假设您有像 txtMyName.tag = 100

这样的文本字段标签
-(void) ClickDone {
      NSIndexPath *indexPath = [[NSIndexPath alloc] indexPathForRow:0 inSection:0];
     UITableViewCell *cell = [tableView cellForRowAtIndexPath:lastIndexPath];
     UITextField *txtField = (UITextField *)[cell viewWithTag:100];
     _strFullName = txtField.text;
  }