菜鸟教程小白 发表于 2022-12-13 14:54:51

ios - 更新数据后 setContentOffset 不起作用


                                            <p><p>我有一个 <code>UITableViewController</code>,当用户滚动到顶部时,我想在第一个单元格上方添加一堆单元格而不影响当前滚动位置(就像 iMessage 一样)</p>

<p>我知道我可以使用 <code>insertRowsAtIndexPaths</code> 来执行此操作而无需重新加载数据,但我只想先以最简单的方式执行此操作。所以我正在覆盖数据并调用<code>reload</code>,然后调用<code>setContentOffset</code>,但无论我将偏移量设置为什么,表格总是回到顶部。</p>

<pre><code>// in an NSNotification handler
//...
dispatch_async(dispatch_get_main_queue(), ^{

// get old content height
CGSize oldContentSize = self.tableView.contentSize;
NSLog(@&#34;old content height: %f&#34;, oldContentSize.height);

// update tableView data
self.messages = updatedMessages;
;

// get new content height
CGSize newContentSize = self.tableView.contentSize;
NSLog(@&#34;new content height: %f&#34;, newContentSize.height);

// move to user scroll position
CGPoint newContentOffset = CGPointMake(0, newContentSize.height - oldContentSize.height);
;
});
</code></pre>

<p>当我运行它时,我得到:</p>

<pre><code>old content height: 557.765625
new content height: 1249.050781
</code></pre>

<p>但是 tableView 恢复到顶部而不是保持其滚动位置。</p>

<p>我发现如果我调用 <code>;</code> 总是向下滚动到正确的位置,但是移动是 Not Acceptable 。</p>

<p>重新加载tableView数据后如何保持滚动位置?</p>

<p>我看过这些:</p>

<p> <a href="https://stackoverflow.com/questions/2917460/setcontentoffset-only-works-if-animated-is-set-to-yes" rel="noreferrer noopener nofollow">setContentOffset only works if animated is set to YES</a> </p>

<p> <a href="https://stackoverflow.com/questions/5882232/uiscrollview-setcontentoffset-animated-not-working" rel="noreferrer noopener nofollow">UIScrollView setContentOffset: animated: not working</a> </p>

<p> <a href="https://stackoverflow.com/questions/15222186/uitableview-contentoffset-is-not-working-properly" rel="noreferrer noopener nofollow">UITableView contentOffSet is not working properly</a> </p>

<p>但他们的解决方案在我的情况下不起作用。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>试试这个</p>

<pre><code>
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 更新数据后 setContentOffset 不起作用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/35690842/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/35690842/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 更新数据后 setContentOffset 不起作用