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

后端 未结 3 1945
梦毁少年i
梦毁少年i 2021-01-20 01:01

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 colle

相关标签:
3条回答
  • 2021-01-20 01:35

    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.

    0 讨论(0)
  • 2021-01-20 01:51

    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
    }()
    
    0 讨论(0)
  • 2021-01-20 01:55

    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:

    0 讨论(0)
提交回复
热议问题