Reputation: 21
I am trying to add a user-editable text field. I was able to get the text field to appear for each different cell of the table, but I wasn't able to get users to input. It doesn't show the keyboard. I have user interaction enabled. This is my code. Please ignore the commented out parts.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "transportCell", for: indexPath)
//self.tableView.rowHeight = 100
//var a = Array(words[indexPath.row])
//a.shuffle()
//var shuffledWord = String(a)
//shuffledWord = shuffledWord.lowercased()
let sampleTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.alphabet
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
// cell.textLabel?.text = shuffledWord
// var imageName = UIImage(named: words[indexPath.row])
//cell.imageView?.image = imageName
return cell
}
If possible could you also tell me how to store the user's input as a variable?
Thanks in advance
Upvotes: 1
Views: 1317
Reputation: 7732
Please refer to this answer see if it helps you.
Upvotes: 0
Reputation: 961
As @rmaddy said that first, you have to add that text field to your cell for that ...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {......
sampleTextField.text = arrTextFieldVal[indexPath.item]//this array for stroing the user input values..
sampleTextField.tag = indexPath.item // u will access the text field with this value
cell.addSubview(sampleTextField)........}
and second, you can store user values by manage an array of string like ...
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrTextFieldVal.count }
and take values from text field delegate like this...
func textFieldDidEndEditing(_ textField: UITextField) {
arrTextFieldVal[textField.tag] = textField.text!
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Upvotes: 3