#ios #swift #text #textview
Вопрос:
У меня есть textview в tableview.Я хочу перейти к следующему текстовому представлению при нажатии клавиши возврата.На данный момент я могу прокрутить табличное представление до следующего индекса, но состояние активного текстового представления не обновляется.
Вот код:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -gt; 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) -gt; Int { return pageCount } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -gt; 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() } }
В textViewDidChange я пытаюсь перейти в textview с индексом 1, но когда я набираю символы, они записываются в textview с индексом 0.Я не могу переключить активное состояние textview в ячейках.
Ответ №1:
Вам нужно сохранить текст для каждой строки.
var text0 = "" func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -gt; 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 ...
Ответ №2:
cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -gt; 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) -gt; 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 }