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

ios - 在 insertRows 之后防止表格 View 滚动到顶部


                                            <p><p>我有viewController,里面有tableView。
这个 tableView 有很多部分和行。
当我尝试在最后一部分中添加新行时,使用
TableView.insertRows(at: , with: .bottom)</p>

<p>tableView 滚动到顶部,并显示当前部分的第一个单元格。</p>

<p>如何防止tableView滚动到顶部?</p>

<p>谢谢</p>

<hr/>

<p>这是我的解决方案</p>

<p>当尝试添加单元格时,我使用此代码</p>

<pre><code>self.didAddNewCell = true
    self.chatTableView.reloadData()
    self.scrollToBottom()
</code></pre>

<p>然后添加这段代码</p>

<pre><code>func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if self.didAddNewCell {

      self.didAddNewCell = false

      let bottomOffset = CGPoint(x: CGFloat(0), y:CGFloat(chatTableView.contentSize.height - self.chatTableView.bounds.size.height))

      scrollView.setContentOffset(bottomOffset, animated: true)

    }

}
</code></pre>

<p>这个滚动到底部的代码</p>

<pre><code>func scrollToBottom() {

    let sections = self.chatTableView.numberOfSections

    if sections &gt; 0 {

      let rows = self.chatTableView.numberOfRows(inSection: sections - 1)

      let last = IndexPath(row: rows - 1, section: sections - 1)

      self.chatTableView.scrollToRow(at: last, at: .none, animated: false)
    }
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><strong>在您的 <code>scrollViewDidScroll</code> 方法中尝试此方法-:</strong></p>

<pre><code>CGPoint bottomOffset = CGPoint(x: CGFloat(0), y:CGFloat(scrollView.contentSize.height - self.scrollView.bounds.size.height))      

    scrollView.setContentOffset(bottomOffset, animated: true)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 在 insertRows 之后防止表格 View 滚动到顶部,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42206030/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42206030/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 在 insertRows 之后防止表格 View 滚动到顶部