I have textview in tableview.I want to move to the next textview when return key is pressed.For now I'm able to scroll the tableview to next index but the state of active textview is not updating.
Here's the code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "editorCell", for: indexPath) as? EditorTableViewCell else{return UITableViewCell()}
cell.textView.delegate = self
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pageCount
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.bounds.height
}
func textViewDidChange(_ textView: UITextView) {
if textView.text.contains(where: {$0 == "\n"}){
self.tableView.scrollToRow(at: IndexPath(row: 1, section: 0), at: .top, animated: true)
self.tableView.layoutIfNeeded()
self.tableView.reloadData()
}
}
In textViewDidChange I try to move to textview at index 1 but when I type characters it gets written in textview at index 0.I'm unable to switch the active state of textview in the cells.
CodePudding user response:
You need to save the text for each row.
var text0 = ""
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "editorCell", for: indexPath) as? EditorTableViewCell else{return UITableViewCell()}
cell.textView.delegate = self
cell.textView.text = self.text0
return cell
}
func textViewDidChange(_ textView: UITextView) {
self.text0 = textView.text
...
CodePudding user response:
CellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.textView.delegate = self
cell.textView.text = "helllo \(indexPath.row)"
cell.textView.tag = indexPath.row
return cell
}
UITextViewDelegate
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
let nextTextViewTag = textView.tag 1
for cell in tableView.visibleCells {
if let nextTextView = cell.viewWithTag(nextTextViewTag) as? UITextView, let indexPath = tableView.indexPath(for: cell) {
nextTextView.becomeFirstResponder()
tableView.scrollToRow(at: indexPath, at: .none, animated: true)
}
}
return false
}
return true
}