I have a problem with custom tableview cell with a textfield. So, I have a separate class for a cell with a textfield, but I can\'t retrieve data in my tableview class. There is
First issue -- in your cell class, in awakeFromNib()
you have:
// CREATE a UITextField
var textField = UITextField()
var data: Dictionary?
override func awakeFromNib() {
super.awakeFromNib()
// assign self as the delegate of textField
textField.delegate = self
let padding = UIView(frame: CGRect(x:0, y:0, width: 15, height: self.frame.height))
// CREATE a NEW UITextField
textField = UITextField(frame: CGRect(x:0, y:0, width: self.frame.width, height: 40))
So, when you create the NEW textField, it no longer has a delegate assigned to it. That's why nothing triggers textFieldShouldReturn
or textFieldDidEndEditing
.
Replace the UITextField(frame: ..)
line with:
textField.frame = CGRect(x:0, y:0, width: self.frame.width, height: 40)
Next, instead of passing in a "data object" to then try and manipulate, think about using a call-back closure.
Change your cell class to this:
class RTextCell: UITableViewCell, UITextFieldDelegate {
var textField = UITextField()
// this will be our "call back" closure
var didEndEditAction : ((String)->())?
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
let padding = UIView(frame: CGRect(x:0, y:0, width: 15, height: self.frame.height))
// just set the frame, don't create a NEW textField
textField.frame = CGRect(x:0, y:0, width: self.frame.width, height: 40)
textField.placeholder = "Your text here"
textField.textColor = UIColor.white
textField.tintColor = UIColor.white
textField.backgroundColor = UIColor.clear
textField.leftView = padding
textField.leftViewMode = .always
self.addSubview(textField)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
print("Should return")
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
// call back using a closure
didEndEditAction?(textField.text ?? "")
}
}
And then configure it like this:
case "textbox":
let rTemplateTextBox = tableView.dequeueReusableCell(withIdentifier: "recapTextCell", for: indexPath) as! RTextCell
rTemplateTextBox.textField.text = cell["data"] as? String ?? "No text"
// setup the "call back" closure
rTemplateTextBox.didEndEditAction = {
(newText) in
let cell = self.myData[indexPath.row]
cell["data"] = newText
}
return rTemplateTextBox