[英]How to set items in collection view go bottom-to-top with swift
I'm making a collection view with fixed height and width and horizontal scroll direction.我正在制作一个具有固定高度和宽度以及水平滚动方向的集合视图。
At the start I will have 1 cell and I want it in the right side of the collection view instead of the left and when more cells are coming I want them to stack in the right side of the previous cell like 1 - 2 - 3.一开始我将有 1 个单元格,我希望它在集合视图的右侧而不是左侧,当更多单元格出现时,我希望它们像 1 - 2 - 3 一样堆叠在前一个单元格的右侧。
I searched for an answer but all similar questions were for objective c.我搜索了一个答案,但所有类似的问题都是针对目标 c。
Any thoughts how could I do this with swift?任何想法我怎么能用swift做到这一点?
Thanks in advance.提前致谢。
The problem is that if you try to set the contentOffset of your collection view in viewWillAppear, the collection view hasn't rendered its items yet.问题是,如果您尝试在 viewWillAppear 中设置集合视图的 contentOffset,集合视图尚未呈现其项目。 Therefore self.collectionView.contentSize is still {0,0}.因此 self.collectionView.contentSize 仍然是 {0,0}。 The solution is to ask the collection view's layout for the content size.解决方案是向集合视图的布局询问内容大小。
Additionally, you'll want to make sure that you only set the contentOffset when the contentSize is taller than the bounds of your collection view.此外,您需要确保仅在 contentSize 高于集合视图的边界时才设置 contentOffset。
func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let contentSize: CGSize? = collectionView?.collectionViewLayout.collectionViewContentSize
if contentSize?.height > collectionView?.bounds.size.height {
let targetContentOffset = CGPoint(x: 0.0, y: (contentSize?.height)! - (collectionView?.bounds.size.height)!)
collectionView?.contentOffset = targetContentOffset
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.