首页 > 解决方案 > 即使我清除了一个数组,iOS UITextViews 数据仍然存在

问题描述

下图显示了UIViewController. 看起来我需要销毁UITextViews在编辑数组后重新创建的其他数据UITextViews。每次进行更改时,我都会将数组设置UITextViews为 [],然后使用更新的数据重新创建它。即使我验证该UITextView数组确实被重置为零元素,然后使用预期的元素数量重新创建,这些幻影图像仍然在屏幕上徘徊,并且调试层次结构显示某些内容没有被删除。

我怀疑我需要做一些整理工作来查找和销毁与 相关的其他数据UITextViews,并且将数组设置回零并不会从我的子视图中清除所有内容,但我不确定这可能是什么。我希望我的错误对于那些有更多经验的人来说是显而易见的,你会指出我正确的方向。

在此处输入图像描述

我还在下面分享了一些代码,但我怀疑视觉可能是有经验的人让我直截了当的最直接线索。

var topOfViewFrame: CGFloat = 0
textViewArray = []
for textBlock in textBlocks.textBlocksArray { // a textBlock has formatting data for a UITextView
    let textBlockHeight = CGFloat(textBlock.numberOfLines) * textBlock.blockFontSize
    let viewFrame = CGRect(x: 0, y: topOfViewFrame, width: textBoxWidth, height: textBlockHeight)
    var newTextView = UITextView(frame: viewFrame)
    newTextView.center = CGPoint(x: screenView.frame.width/2, y: topOfViewFrame + (textBlockHeight/2)) // screenView is the 320x240 subView holding the [UITextViews]
    let viewFont = UIFont(name: "AvenirNextCondensed-Medium", size: textBlock.blockFontSize)
    newTextView.font = viewFont
    newTextView.text = textBlock.blockText
    newTextView = configureTextBlockView(textBoxView: newTextView, textBlock: textBlock)
    textViewArray.append(newTextView)
    screenView.addSubview(newTextView) // screenView is the subview holding the [UITextViews]
    topOfViewFrame += newTextView.frame.height // put the next UITextView directly below the previous one
}

谢谢!

标签: iosarraysswiftuiviewcontrolleruitextview

解决方案


如果您想从“screenView”中删除所有 textView,仅清除数组是不够的。您需要将其从 superview 中删除:

screenView.subviews.forEach({ $0.removeFromSuperview() })

推荐阅读