Swift在.xib文件中检测文本字段中的更改
问题描述:
我的问题是我在可扩展表格视图内部有一个文本框,由cellDescription plist指定。在此表格视图中,当地址部分展开时,会弹出一个文本字段,用户可以在其中输入地址。用户必须在键盘上按回车键(或输入)才能保存地址。我想知道是否有一种方法可以检测文本字段中的变化,这种变化可以不断更新文本字段的值,这样用户就不必输入return来保存地址。下面是我的代码目前的结构,但我很困惑,因为文本字段不在常规视图控制器内,而是在外部xib文件中。Swift在.xib文件中检测文本字段中的更改
func configureTableView() {
tblExpandable.delegate = self
tblExpandable.dataSource = self
tblExpandable.tableFooterView = UIView(frame: CGRect.zero)
tblExpandable.register(UINib(nibName: "TextfieldCell", bundle: nil), forCellReuseIdentifier: "idCellTextfield")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let currentCellDescriptor = getCellDescriptorForIndexPath(indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: currentCellDescriptor["cellIdentifier"] as! String, for: indexPath) as! CustomCell
if currentCellDescriptor["cellIdentifier"] as! String == "idCellTextfield" {
cell.textField.placeholder = currentCellDescriptor["primaryTitle"] as? String
valueOfInterest = cell.textField.text!
}
cell.delegate = self
return cell
}
func textfieldTextWasChanged(_ newText: String, parentCell: CustomCell) {
let parentCellIndexPath = tblExpandable.indexPath(for: parentCell)
var address = ""
address = "\(newText)"
((cellDescriptors[0] as! NSMutableArray)[11] as AnyObject).setValue(address, forKey: "primaryTitle")
location = (((cellDescriptors[0]) as! NSMutableArray)[11] as! NSDictionary)["primaryTitle"]! as! String
tblExpandable.reloadData()
}
答
在这里,您的CustomCell中有文本字段。所以设置文本字段的出口在CustomCell类如:
@IBOutlet weak var textField:UITextField!
然后设置CustomCell类作为文本框的委托,并实现文本字段的所需委托方法来检测在TextField中的值的变化。
如何将CustomCell类设置为textField的委托,因为此swift文件没有“override func viewDidLoad(){}”? – Kevin
为什么您需要viewDidLoad()方法来设置委托。您可以从自定义单元类的xib文件或awakeFromNib()方法中设置委托。 –
试图在awakeFromNib()中设置如下代理:“textField.delegate = self”在模拟器中运行时导致错误:致命错误:意外地在解包可选值时发现nil。我没有正确设置委托吗? – Kevin