我有一个包含多个原型单元的表格视图。我想在这些单元格中获取textField的值并在点击按钮时追加一个数组。
单元格有一个称为element的对象。我想将此元素附加到我的视图控制器中的elementsArray中。问题是当cellForRow方法工作时会创建此元素键,但是由于cellForRowAt方法只能工作一次,因此元素对象的“值”键取txtContent的初始值。
在为每个单元格编写文本后如何获取txtContent文本?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let object = surveyDetailArray.first!.elements[indexPath.row]
switch object.type {
case CellConfig.email.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: "EmailCell", for: indexPath) as! EmailCell
cell.lblTitle.text = object.title
cell.txtContent.inputAccessoryView = toolBar
cell.element["formElementId"] = object.id as AnyObject
cell.element["options"] = optionArray as AnyObject
elementsArray.append(cell.element as AnyObject)
return cell
case CellConfig.number.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: "NumberCell", for: indexPath) as! NumberCell
cell.lblTitle.text = object.title
cell.txtContent.inputAccessoryView = toolBar
cell.txtContent.keyboardType = .numberPad
cell.element["formElementId"] = object.id as AnyObject
cell.element["options"] = optionArray as AnyObject
elementsArray.append(cell.element as AnyObject)
return cell
}
我的手机班
class EmailCell: UITableViewCell,UITextFieldDelegate {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var txtContent: CustomTextField!
var element = ["formElementId":"",
"value":"",
"options":[]] as [String : Any]
override func awakeFromNib() {
super.awakeFromNib()
txtContent.backgroundColor = #colorLiteral(red: 0.1570051014, green: 0.1588717997, blue: 0.2081049681, alpha: 0.1)
txtContent.layer.borderWidth = 0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
txtContent.delegate = self
// Configure the view for the selected state
}
func textFieldDidEndEditing(_ textField: UITextField) {
element["value"] = textField.text!
}
}
答案 0 :(得分:0)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let object = surveyDetailArray.first!.elements[indexPath.row]
switch object.type {
case CellConfig.email.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: "EmailCell", for: indexPath) as! EmailCell
cell.txtContent.delegate = self
return cell
case CellConfig.number.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: "NumberCell", for: indexPath) as! NumberCell
return cell
}
extension ViewController: UITextFieldDelegate{
func textFieldDidEndEditing(_ textField: UITextField) {
var cell: UITableView Cell!
if let emailCell: UITableViewCell = textField.superview.superview as? EmailCell{
cell = emailCell
}
if let numbCell: UITableViewCell = textField.superview.superview as? NumberCell{
cell = numbCell
}
var table: UITableView = cell.superview as UITableView
let textFieldIndexPath = table.indexPathForCell(cell)
// HERE DO THE UPDATION YOU WANT TO DO
}
}