How to set the collection view cell size exactly e

2020-04-09 17:56发布

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).

Any help will be really appreciated.

3条回答
小情绪 Triste *
2楼-- · 2020-04-09 18:29

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
}()
查看更多
地球回转人心会变
3楼-- · 2020-04-09 18:47

Simple answer :

Add UICollectionViewDelegateFlowLayout to your class and then use this method:

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:

enter image description here

查看更多
ゆ 、 Hurt°
4楼-- · 2020-04-09 18:48

Try this code:

To set collectionView scroll Direction Programmically.

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

To set collectionView layout

     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.

查看更多
登录 后发表回答