菜鸟教程小白 发表于 2022-12-11 18:56:10

ios - Tableviewcell 内容在滚动时四处移动


                                            <p><p>我遇到了一个问题,我找不到任何解决方案..</p>

<p>基本上我有一个 UITableview 和单元格的内容只是一个 UITextField。我通过单击按钮向此 TableView 添加另一行。在这里,我将 1 添加到一个计数器,它在我的 tableView 中显示“numberOfRowsInSection”。所以基本上计数器在 3 开头,所以开头有 3 个文本字段。现在我可以通过增加计数器来动态添加另一行。按下按钮后,tableview 会重新加载其数据。</p>

<p>所以这是一个代码片段..</p>

<pre><code>@IBAction func addPlayer(_ sender: UIButton) {
    counterPlayer += 1
    tableView.reloadData()
    tableViewScrollToBottom(animated: true)
}



func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
    return counterPlayer
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: &#34;PlayerTableViewCell&#34;, for: indexPath) as! PlayerTableViewCell
    cell.tag = indexPath.row + 1

    cell.playerTextField.placeholder = &#34;Spieler &#34; + String(indexPath.row + 1)

    return cell
}
</code></pre>

<p>它工作得很好,但是如果我在第一个文本字段中写一些东西,添加更多行然后开始滚动,随机文本字段的内容与第一个文本字段相同。第一个文本字段的内容也随机移动到其他文本字段。这是一个gif,所以你可以更好地想象。</p>

<p> <a href="/image/aqWFr.gif" rel="noreferrer noopener nofollow"><img src="/image/aqWFr.gif" alt="enter image description here"/></a> </p>

<p>我认为问题是“dequeueReusableCell”,所以当我滚动时,第一个文本字段会消失,所以它们会被重用并且仍然具有旧的内容。</p>

<p>不幸的是,当我再次向上滚动时,我不知道保存旧值并显示它们的好方法......
当我不使用 reusableCell 而只是创建新的独特单元格时,我可以解决这个问题,但我认为这不是一个好的解决方案。
你有什么建议,我该如何解决我的问题?
我想我需要以某种方式缓存已经填充的内容,然后在向上滚动时再次显示它......但是如何?</p>

<p>要了解我想在这里做什么:
基本上,用户可以输入“玩家姓名”,然后点击按钮执行转场并开始游戏。因此,当他点击按钮时,所有 tableviewcells 的文本都应该使用数组传递。
他没有任何玩家人数限制。</p>

<p>期待您的回答。非常感谢!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可以通过覆盖 <code>UITableViewCell</code> 的 <code>prepareForReuse</code> 方法并清除旧数据来解决此问题。</p>

<pre><code>override func prepareForReuse() {
    super.prepareForReuse()

    // Clear old data to prepare the cell for being reused.
}
</code></pre>

<p><strong>更新:</strong>要解决未保存值的问题,我建议您创建一个数组来保存每个 <code>indexPath.row</code> 的未保存数据。</p>

<p>因此,在 <code>cellForRow</code> 方法中,您将使用 <code>indexPath.row</code> 中的数组数据设置文本字段的当前文本。当您完成对文本字段的编辑后,您将输入的数据保存在该数组中合适的 <code>indexPath</code> 处。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Tableviewcell 内容在滚动时四处移动,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/46613958/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/46613958/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Tableviewcell 内容在滚动时四处移动