UICollectionView 双向滚动 [英] UICollectionView scrolling in both directions
问题描述
我制作了一个带有垂直滚动的 UICollectionView
.
单元格的宽度大于屏幕宽度,所以我基于 UICollectionViewFlow
布局创建了一个 customFlowLayout
返回正确计算的内容大小.
然而,这行不通.当单元格的宽度小于屏幕宽度时,它会起作用.这是否意味着垂直滚动时我们的宽度不能超过屏幕宽度?
水平滚动也是一样,但是CollectionView
的高度受限于屏幕高度.
有什么办法让它工作吗?
正如其他人已经说过的,UICollectionView
只能使用流布局滚动一个方向.但是,您无需创建自定义布局或使用第三方库即可轻松完成此操作.
当您在故事板中布置视图时,您可以将 UICollectionView
嵌入到 UIScrollView
中.将滚动视图设置为水平滚动,将 UICollectionView
设置为垂直滚动.然后将 UICollectionView.delaysContentTouches
设置为 true,这样触摸就会传递到 UIScrollView
并且不会认为您正在尝试滚动 collectionview.
当您设置 UICollectionView
时,将其大小和单元格的大小设置为您实际想要的大小(比实际屏幕更宽)并相应地进行布局.>
现在在包含 UIViewController
中将此代码放入视图生命周期
- (void)viewDidLayoutSubviews {self.myScrollView.contentSize = self.myCollectionView.frame.size;}
这就是您要完成所描述的内容所需要做的全部工作.现在您的滚动视图应该允许您水平滚动以查看整个单元格,您的 collectionView 应该可以垂直滚动您的单元格.
快乐编程.
I made a UICollectionView
with a vertical scroll.
The width of the cell is more than than the screen width, so I created a customFlowLayout
based on UICollectionViewFlow
layout returning the right calculated content size.
However, this doesn't work. When the width of the cell is less than the screen width it works. Does it mean that we can't have width more than than screen width in vertical scroll?
It is the same for horizontal scroll, but then the height of the CollectionView
is limited to screen height.
Is there any way to make it work?
As others have already said, the UICollectionView
can only scroll one direction using a flow layout. However you can accomplish this very easily without creating a custom layout or using a third party library.
When you lay your view out in story board, you can put your UICollectionView
embedded in a UIScrollView
. Have the scrollview set up to scroll horizontally and the UICollectionView
to scroll Vertically. Then set the UICollectionView.delaysContentTouches
to true so touches will pass through to the UIScrollView
and not think you are trying to scroll the collectionview.
When you set up the UICollectionView
, set it's size and the size of the cells to be what you actually want them to be (Wider than the actual screen) and lay them out accordingly.
Now in the containing UIViewController
put this code in the view lifecycle
- (void)viewDidLayoutSubviews {
self.myScrollView.contentSize = self.myCollectionView.frame.size;
}
That's literally all you have to do to accomplish what you are describing. Now your scrollview should allow you to scroll horizontally to view your entire cell and your collectionView should scroll vertically through your cells.
Happy programming.
这篇关于UICollectionView 双向滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!