首页 > 解决方案 > 自定义 UITableViewCell 类 IOS 中文本字段中的空字符串

问题描述

我为 UITableViewCell 创建了一个自定义类。UITableViewCell 是故事板中的一个动态原型单元。我正在尝试从我的主视图控制器中的 textfield.text 引用字符串。我在主视图控制器中的代码为 textfield.text 字符串返回 nil。我知道对单元格的引用是正确的,因为它会自动填充 textfield.text,但仍然返回 nil。请帮忙。

class AddMyLayerTitleCell: UITableViewCell, UITextFieldDelegate {

@IBOutlet weak var addMyLayerTitleTF: UITextField!


override func awakeFromNib() {
    super.awakeFromNib()
    
    self.addMyLayerTitleTF.becomeFirstResponder()
    self.addMyLayerTitleTF.delegate = self
    
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
  textField.resignFirstResponder()

    // This works
    print("text field text = \(addMyLayerTitleTF.text!)")

    return true
}  
}

MainViewController.m  - (objective-c)

- (IBAction)addMyLayerSaveButton:(id)sender {

    AddMyLayerTitleCell *cell = [self.gisTableView dequeueReusableCellWithIdentifier:@"AddTitleCell"];
    NSString *myLayerString = cell.addMyLayerTitleTF.text;

    // Returns nil
    NSLog(@"myLayerString = %@", myLayerString);
    NSLog(@"myLayerString = %@", cell.addMyLayerTitleTF.text);
   

}

标签: iosobjective-cswiftuitextfield

解决方案


问题是我必须删除AddMyLayerTitleCell *cell = [self.gisTableView dequeueReusableCellWithIdentifier:@"AddTitleCell"];按钮中的行。这在我从中请求文本字段字符串之前创建了一个新的单元格实例,因此在我获取它时新单元格的文本字段中将没有任何内容。我还必须AddMyLayerTitleCell *cell;在类外部声明,以便可以从按钮引用现有单元格。

class AddMyLayerTitleCell: UITableViewCell, UITextFieldDelegate {

@IBOutlet weak var addMyLayerTitleTF: UITextField!

    override func awakeFromNib() {
    super.awakeFromNib()

    self.addMyLayerTitleTF.becomeFirstResponder()
    self.addMyLayerTitleTF.delegate = self

}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate  method
 textField.resignFirstResponder()

    // This works
    print("text field text = \(addMyLayerTitleTF.text!)")

    return true
}

}


// MainViewController.m  - (objective-c)

AddMyLayerTitleCell *cell;

@interface MainViewController ()


- (IBAction)addMyLayerSaveButton:(id)sender {
    
    NSString *myLayerString = cell.addMyLayerTitleTF.text;

    // Works
    NSLog(@"myLayerString = %@", myLayerString);
    NSLog(@"myLayerString = %@", cell.addMyLayerTitleTF.text);

}

推荐阅读