简体   繁体   English

如何在集合视图中设置项目快速自下而上

[英]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.

相关问题 如何将项目追加到表或集合视图的底部? - How to append items to the bottom of the table or collection view ? Swift - 将标签设置在其他视图项的顶部 - Swift - Set label to be on top of other view items 如何将一个视图的顶部设置为另一个视图的底部 - How to set top of a view to bottom of another view 如何创建一个滚动视图,顶部视图是集合视图,底部是列表? - How to create a scrollable view with a collection view on the top and the list on the bottom? 如何在Swift 4中从CollectionView的底部到Input Accessory View的顶部设置约束 - How to set constraints from the bottom of a collectionView to the top of Input Accessory View in Swift 4 Swift UITableView - 如何将新项目放在列表的顶部而不是底部? - Swift UITableView - How to put new items on top not on the bottom of the list? 如何在swift4中为图库从底部到顶部设置动画 - How to animate a view from bottom to top for gallery in swift4 如何在集合视图单元的内部底部边缘添加阴影? 迅捷3 - How to add a shadow to the inside bottom edge of a collection view cell? swift 3 如何设置UIToolBarPosition顶部或底部 - How to set UIToolBarPosition Top or bottom 如何在 Swift 中的集合视图和单元格内设置约束 - How to set constraints in Collection View and inside Cells in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM