【发布时间】:2020-01-22 03:02:15
【问题描述】:
我有一个集合视图,我正在为单元格使用自定义类。每个单元格有两个文本视图,chapterTitleTextView 和 chapterBodyTextView。我在两个文本视图中都添加了占位符,如下所示:
class CustomWriterPageCell: UICollectionViewCell, UITextViewDelegate {
// When the user taps on a text view
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == .gray {
textView.text = nil
textView.textColor = .black
}
}
// When the user taps out of a text view or taps on the done button in the toolbar
func textViewDidEndEditing(_ textView: UITextView) {
// If the chapter title text view is empty
if chapterTitleTextView.text.isEmpty {
chapterTitleTextView.text = "Chapter Title"
chapterTitleTextView.textColor = .gray
}
// If the chapter body text view is empty
if chapterBodyTextView.text.isEmpty {
chapterBodyTextView.text = "Chapter Body"
chapterBodyTextView.textColor = .gray
}
}
}
它的工作原理是,文本颜色最初是灰色的,并且有一些文本,当用户点击文本视图时,颜色变为黑色,文本视图中的文本被删除。
现在使用 dequeueReusableCell 存在这个问题,它重用了单元格,这导致了问题 1:无论我在第一个单元格的文本视图中键入的内容出现在第 4 个单元格上,为了解决这个问题,我必须创建2 个全局列表来保存我输入的任何内容,这会显示在单元格的文本视图中,代码如下:
全局列表:
var chapterTitleText = Array(repeating: "", count: 4) // To store the chapter title text
var chapterBodyText = Array(repeating: "", count: 4) // To store the chapter body text
下面的代码 sn-p 在之前的 textViewDidEndEditing 中
// Append the chapter body text to the chapterBodyText array
let titleText = chapterTitleTextView.text
let titleRow = textView.tag //This the indexPath.row
chapterTitleText[titleRow] = titleText!
// Append the chapter title text to the chapterTitleText array
let bodyText = chapterBodyTextView.text
let bodyRow = textView.tag
chapterBodyText[bodyRow] = bodyText!
在 cellForItemAt 中:
cell.chapterBodyTextView.tag = indexPath.row
cell.chapterTitleTextView.tag = indexPath.row
cell.chapterTitleTextView.text = chapterTitleText[indexPath.row]
cell.chapterBodyTextView.text = chapterBodyText[indexPath.row]
这消除了第 1 个问题(文本视图中的文本重复)。但是后来我遇到了一个新问题,还记得我说的占位符文本吗?当我在第一个单元格的一个文本视图中键入内容时,第四个单元格中的文本视图的文本颜色会发生变化。我将添加一个重现问题的 GIF 以帮助读者理解:
【问题讨论】:
标签: ios swift textview uicollectionview