简体   繁体   English

如何设置集合视图单元格大小与iOS中的集合视图完全相同?

[英]How to set the collection view cell size exactly equal to the collection view in iOS?

I want to set a collection view where it is only displayed one element at the time and it scrolls horizontally. 我想设置一个集合视图,它只显示一个元素,并且水平滚动。 I want to know how to set the same size for both if the collection view has equal width with the superview (phone size). 我想知道如果集合视图与superview(手机大小)具有相同的宽度,如何为两者设置相同的大小。

Any help will be really appreciated. 任何帮助将非常感激。

Simple answer : 简单回答:

Add UICollectionViewDelegateFlowLayout to your class and then use this method: UICollectionViewDelegateFlowLayout添加到您的类,然后使用此方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: yourCollectionView.bounds.width, height: yourCollectionView.bounds.height)
}

to make it horizontal: 使其水平:

在此输入图像描述

if you want to add it programmatically you can try this: 如果你想以编程方式添加它,你可以试试这个:

lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.delegate = self
        cv.dataSource = self
        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        return cv
}()

Try this code: 试试这段代码:

To set collectionView scroll Direction Programmically. 要以编程方式设置collectionView滚动方向。

override func viewDidLoad() {
    super.viewDidLoad()
       if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
       layout.scrollDirection = .horizontal
    }
    }

To set collectionView layout 设置collectionView布局

     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
      let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
      layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
      layout.minimumInteritemSpacing = 0
      layout.minimumLineSpacing = 0
      layout.invalidateLayout()

      return CGSize(width: self.view.frame.width, height:(self.view.frame.height) // Set your item size here
     }

Note : Layout works tested in Swift 3. But, I want you to consider using page view instead.If you not passing any data from CollectionView. 注意 :布局在Swift 3中进行了测试。但是,我希望您考虑使用页面视图。如果您没有从CollectionView传递任何数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM