【发布时间】:2021-01-24 02:09:59
【问题描述】:
我有一个使用 UITextViews 的自定义单元格的表格视图。每当用户在单元格的 textView 中编辑文本然后点击返回时,都会将一个新单元格插入到填充表格视图单元格的数据列表中,并调用 tableView.reloadData() 以便新单元格立即显示。用户按下返回时正在编辑的单元格的 textView.tag + 1 存储为名为 cellCreatedWithReturn 的变量,如果重新加载 tableView 时该变量不为零,则具有该 indexPath.row 的单元格(因此新单元格刚刚创建的)成为第一响应者。
我遇到的问题是,当我按回车键时,会创建新单元格并将其分配为第一响应者,但键盘会因为它开始隐藏然后重新弹起,而不仅仅是留在原地。演示我正在寻找的功能的应用程序是 Apple 的提醒应用程序。当您按回车键时,会创建一个新单元格并在该新单元格上开始编辑,但键盘始终保持打开状态而不会发出声音。
我尝试的一件事是从我的 shouldChangeTextIn 函数中注释掉 textView.endEditing(true) 以查看这是否是键盘被降低的原因,但这并没有导致任何变化。
这是我的 shouldChangeTextIn 和 cellForRowAt 函数:
var cellCreatedWithReturn: Int?
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
textView.endEditing(true)
cellCreatedWithReturn = textView.tag + 1
if song.lyrics.count == textView.tag || song.lyrics[textView.tag].text != "" {
let newLyricLine = LyricLine()
newLyricLine.text = ""
do {
try realm.write {
self.song.lyrics.insert(newLyricLine, at: textView.tag)
print("Successfully inserted new lyric line in Realm")
}
} catch {
print("Error when inserting new lyric line after pressing return")
}
}
tableView.reloadData()
return false
} else {
return true
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "lyricsCell", for: indexPath) as! newNoteTableViewCell
cell.lyricsField.delegate = self
DispatchQueue.main.async {
if let newCellIndexPath = self.cellCreatedWithReturn {
if indexPath.row == newCellIndexPath {
cell.lyricsField.becomeFirstResponder()
}
}
}
}
【问题讨论】:
标签: ios swift uitableview textview first-responder