UICollectionViewFlowLayout在方向更改时不会失效

xxt*_*axx 22 ios uicollectionview uicollectionviewlayout

我有一个带有UICollectionViewFlowLayout的UICollectionView.我还实现了UICollectionViewDelegateFlowLayout协议.

在我的数据源中,我有一堆UIViewControllers响应自定义协议,所以我可以询问它们的大小和其他一些东西.

在FlowLayout委托中,当它要求sizeForItemAtIndexPath:时,我返回从我的协议获得的项目大小.实现我的协议的ViewControllers根据方向返回不同的项目大小.

现在,如果我将设备方向从纵向更改为横向,则没有问题(项目在横向上更大)但如果我将其更改回来,我会收到此警告:

    the item width must be less that the width of the UICollectionView minus the section insets left and right values.
    Please check the values return by the delegate.
Run Code Online (Sandbox Code Playgroud)

它仍然有效,但我不喜欢它得到警告所以也许你可以告诉我我做错了什么.还有另一个问题.如果我没有告诉我的collectionViews collectionViewLayout在willAnimateRotationToInterfaceOrientation中失效:从不调用sizeForItemAtIndexPath :.

希望你明白我的意思.如果您需要其他信息,请告诉我:)

Bob*_*eld 35

答案很晚,但接受的答案对我不起作用.我同情OP需要一个即兴发射的UICollectionViewFlowLayout.我建议在视图控制器中使布局无效实际上是最好的解决方案.

我想要一个单独的水平滚动细胞线,在视图中居中,纵向和横向.

我将UICollectionViewFlowLayout子类化.

我overrode prepareLayout重新计算插入,然后调用[super prepareLayout].

我推翻了getter方法collectionViewContentSize使某些内容大小是正确的.

即使边界随着重新定向而变化,布局也不会自动失效.

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // does the superclass do anything at this point?
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

    // do whatever else you need before rotating toInterfaceOrientation

    // tell the layout to recalculate
    [self.collectionViewLayout invalidateLayout];
}
Run Code Online (Sandbox Code Playgroud)

UICollectionViewFlowLayout维护方向之间的滚动位置.只有当它是正方形时,相同的单元格才会居中.


cyn*_*six 8

我在这里使用了两个答案的组合来做我们都想要做的事情真的是使集合视图看起来像表视图但不使用UITableView并在单个列中获取项目(很可能)

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    [self.collectionView.collectionViewLayout invalidateLayout];
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议你使布局无效而不是重新加载数据. (2认同)

kwi*_*gbo 0

一种解决方案是使用 KVO 并侦听集合视图的超级视图框架的更改。调用 -reloadData 将起作用并消除警告。这里有一个潜在的时间问题......

// -loadView
[self.view addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];

// -dealloc
[self.view removeObserver:self forKeyPath:@"frame"];

// KVO Method
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [collectionView_ reloadData];
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能有效,但根据文档,UIView 框架不符合 KVO,Bob Wakefield 的答案与任何 hack 无关。 (2认同)