菜鸟教程小白 发表于 2022-12-13 09:56:01

ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局


                                            <p><p>我正在创建一个水平滚动的分页 UICollectionView,其单元格与 Collection View 一样大,因此一次只显示一个单元格。我还想在 Collection View 首次出现时首先显示最后一个项目,以便从左侧显示其他项目,而不是从右侧显示下一个项目的默认值。</p>

<p>为此,我按照 <a href="https://stackoverflow.com/a/20084341/855680" rel="noreferrer noopener nofollow">this answer</a> 的建议在 ViewController 的 <code>viewDidLayoutSubviews</code> 中调用 <code>scrollToItemAtIndexPath:</code> .如果我在 viewWillAppear 或 <code>viewDidLoad</code> 中调用 <code>scrollToItemAtIndexPath</code>,则 Collection View <strong>根本不会</strong>滚动到最后一项。</p>

<p>但是,此调用破坏了我的 Collection View 单元格的布局。例如,如果我不调用 <code>scrollToItemAtIndexPath:</code>,则 Collection View (下方的白色区域)看起来像左边的——布局正确但显示了第一个项目。如果我调用 <code>scrollToItemAtIndexPath:</code>, Collection View 最初会显示最后一项,但布局会像右侧一样困惑(甚至不再显示日期)。</p>

<p> <img src="/image/DIMgV.png" alt="enter image description here"/> </p>

<p>我做错了什么?</p>

<p>更多信息:</p>

<ul>
<li>我在 iOS 7 和 iOS 8 中都看到了这个错误。</li>
<li>我在 Xcode 6.1 中使用尺寸类。</li>
</ul>

<p>viewDidLayoutSubviews 的代码:</p>

<pre><code>- (void)viewDidLayoutSubviews
{
    ;

    NSIndexPath *lastIndexPath = ;
    ;
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>每当我遇到这个问题并且我有一个恒定大小的单元格时,我都会通过手动设置 contentOffset 并忽略 collectionView 方法来解决它。</p>

<pre><code>self.collectionView.contentOffset = (CGPoint){
.x = self.collectionView.contentSize.width - cell.width,
.y = 0,
};
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/26947366/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/26947366/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局