我正在尝试添加一个用户可编辑的文本字段。我能够让文本字段出现在表格的每个不同单元格中,但我无法让用户输入。它不显示键盘。我启用了用户交互。这是我的代码。请忽略注释掉的部分。
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
}
如果可能的话,你能告诉我如何将用户的输入存储为变量吗?
提前致谢
最佳答案
正如@rmaddy 所说,首先,您必须将该文本字段添加到您的单元格中...
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)........}
其次,您可以通过管理字符串数组来存储用户值,例如...
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrTextFieldVal.count }
并像这样从文本字段委托(delegate)中获取值...
func textFieldDidEndEditing(_ textField: UITextField) {
arrTextFieldVal[textField.tag] = textField.text!
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
关于ios - 用户输入不适用于在表格 View 中以编程方式添加的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759200/