xcode CollectionViewController scrollToItemAtIndexPath 不起作用

标签 xcode

我创建了一个 CollectionView控制并用图像填充它。现在我想在开始时滚动到特定索引处的项目。我试过scrollToItemAtIndexPath如下:

[self.myFullScreenCollectionView scrollToItemAtIndexPath:indexPath 
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

但是,我遇到了以下异常。谁能指导我哪里出错了。
2013-02-20 02:32:45.219 ControlViewCollection1[1727:c07] *** Assertion failure in 
-[UICollectionViewData layoutAttributesForItemAtIndexPath:], /SourceCache/UIKit_Sim/UIKit-2380.17
/UICollectionViewData.m:485 2013-02-20 02:32:45.221 ControlViewCollection1[1727:c07] must return a 
UICollectionViewLayoutAttributes instance from -layoutAttributesForItemAtIndexPath: for path 
<NSIndexPath 0x800abe0> 2 indexes [0, 4]

最佳答案

从 iOS 9.3、Xcode 8.2.1、Swift 3 开始:

调用scrollToItem(at:)来自 viewWillAppear()仍然损坏,特别是如果您使用的是部分页眉/页脚、自动布局、部分插图。

即使您调用setNeedsLayout()layoutIfNeeded()collectionView ,行为仍然很无聊。将滚动代码放入动画 block 并不可靠。

如其他答案所示,解决方案是只调用 scrollToItem(at:)一旦你确定一切都已经布置好了。即在 viewDidLayoutSubviews() .

但是,您需要有选择性;您不想每次都执行滚动viewWillLayoutSubviews()叫做。所以解决方法是在viewWillAppear() 中设置一个标志。 ,并在 viewDidLayoutSubviews() 中对其进行操作.

IE。

fileprivate var needsDelayedScrolling = false

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)
    self.needsDelayedScrolling = true
    // ...
}

override func viewDidLayoutSubviews()
{
    super.viewDidLayoutSubviews()

    if self.needsDelayedScrolling {
        self.needsDelayedScrolling = false
        self.collectionView!.scrollToItem(at: someIndexPath,
                at: .centeredVertically,
                animated: false)
        }
    }
}

关于xcode CollectionViewController scrollToItemAtIndexPath 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14977896/

相关文章:

python - Xcode 4 上的 PyObjC

Xcode 将语义问题显示为错误

iphone - 管理多个按下的 UIButton

iphone - 只编辑 uitableview 的一部分

xcode - 将上下文管理器添加到单个 View 应用程序

swift - print() 使用颜色来控制日志

ios - 为什么我的 UIViewController 子类有时会自动导入 Cocoa,有时会自动导入 UIKit

xcode - 调试初始化程序时出现问题?

ios - 以编程方式在 Swift 中的选项卡之间切换

php - 使用 AWS IAM 的临时凭证