ios - 自定义 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);
}
解决方案
问题是我必须删除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);
}
推荐阅读
- mysql - 如何将所有记录从 Column1 复制到同一张表的 Column2?
- java - 测试NG。将 testng-results 更改为不包含配置方法
- python - 使用 Scrapy 抓取网页
- git - 如何删除 git 远程源并添加新的远程源?
- ios - 如何在 kizoa 应用程序中制作图像/视频过渡动画
- c# - 无法从 tcp 服务器读取数据
- ionic4 - Ionic 4 Capacitor 选择适用于 Android 和 IOS 的文件
- angular - Angular 材质深色主题
- ionic-framework - 位置不可用电容器离子
- arrays - 运行包含大量原始数据的查询