为什么我的 UICollectionView 单元格在滚动后消失了?
Why Do My UICollectionViewCells Disappear After Scroll?
我正在使用带有自定义布局的 UICollectionView
,但我遇到了问题,即在向下滚动并向上滚动后单元格会消失。
请查看我的问题video demonstration。
我在谷歌上搜索了一下,其他人也有相关问题,我认识到这可能是由于单元重复使用造成的,但是 none 我在别处找到的答案对我有帮助。
所以我的问题是:
为什么会这样?
如何阻止这种情况发生?
有趣的是,一旦我提出 UIViewController
并关闭它,问题就不再发生。请查看此操作的 video。
注意:这个错误已经存在一段时间了(至少从 iOS 10 开始,并且在 iOS 11 beta 1 中也没有修复)。
编辑 1
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch (indexPath as NSIndexPath).row {
case 0:
// Speak Logo Cell
let speakLogoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpeakLogoCell", for: indexPath) as! SpeakLogoCell
recordButton = speakLogoCell.recordButton
return speakLogoCell
case 1:
// Text Input Cell
let inputCell = collectionView.dequeueReusableCell(withReuseIdentifier: "InputCell", for: indexPath) as! InputCell
inputCell.inputTextView.delegate = self
inputTextView = inputCell.inputTextView
// Only restore input if launching and required.
if currentlyLaunching && UserDefaultsHelper.loadShouldRestoreInput() {
inputTextView!.text = UserDefaultsHelper.loadInput() ?? ""
}
return inputCell
case 2:... // Continues for all the other cells
这可能与您将输入视图分配给变量有关。通常我只是将输入视图中的文本存储在一个变量中,而不是让一个变量指向文本视图本身。您可能会更改该行为并查看它是否会发生变化,或者只是暂时注释掉您将输入视图设置为变量的部分并查看它是否会发生任何变化。
想通了。所以导致问题的代码行实际上在 viewDidAppear
中,它是:
inputTextView?.becomeFirstResponder()
我不知道为什么它导致单元格不出现,但删除该行解决了问题。
我正在使用带有自定义布局的 UICollectionView
,但我遇到了问题,即在向下滚动并向上滚动后单元格会消失。
请查看我的问题video demonstration。
我在谷歌上搜索了一下,其他人也有相关问题,我认识到这可能是由于单元重复使用造成的,但是 none 我在别处找到的答案对我有帮助。
所以我的问题是:
为什么会这样?
如何阻止这种情况发生?
有趣的是,一旦我提出 UIViewController
并关闭它,问题就不再发生。请查看此操作的 video。
注意:这个错误已经存在一段时间了(至少从 iOS 10 开始,并且在 iOS 11 beta 1 中也没有修复)。
编辑 1
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch (indexPath as NSIndexPath).row {
case 0:
// Speak Logo Cell
let speakLogoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpeakLogoCell", for: indexPath) as! SpeakLogoCell
recordButton = speakLogoCell.recordButton
return speakLogoCell
case 1:
// Text Input Cell
let inputCell = collectionView.dequeueReusableCell(withReuseIdentifier: "InputCell", for: indexPath) as! InputCell
inputCell.inputTextView.delegate = self
inputTextView = inputCell.inputTextView
// Only restore input if launching and required.
if currentlyLaunching && UserDefaultsHelper.loadShouldRestoreInput() {
inputTextView!.text = UserDefaultsHelper.loadInput() ?? ""
}
return inputCell
case 2:... // Continues for all the other cells
这可能与您将输入视图分配给变量有关。通常我只是将输入视图中的文本存储在一个变量中,而不是让一个变量指向文本视图本身。您可能会更改该行为并查看它是否会发生变化,或者只是暂时注释掉您将输入视图设置为变量的部分并查看它是否会发生任何变化。
想通了。所以导致问题的代码行实际上在 viewDidAppear
中,它是:
inputTextView?.becomeFirstResponder()
我不知道为什么它导致单元格不出现,但删除该行解决了问题。