首页 > 解决方案 > 单元格部分可见的 UICollectionView

问题描述

我想做一个可以水平滚动的collectionView,只有一个单元格项目可见,一个部分可见。单元格应占据 collectionView 的整个高度。

我玩过collectionView的sectionInset。但无法达到我的目标。

我的代码:

import UIKit

class BooksController: UIViewController {

    @IBOutlet weak var booksCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()


        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20)
        layout.itemSize = CGSize(width: booksCollectionView.frame.width, height: booksCollectionView.frame.height)
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.scrollDirection = .horizontal
        booksCollectionView.collectionViewLayout = layout


        booksCollectionView.register(UINib(nibName: "BookCell", bundle: .main), forCellWithReuseIdentifier: "BookCell")
        booksCollectionView.dataSource = self
        booksCollectionView.delegate = self
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension BooksController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BookCell", for: indexPath) as? BookCell {
            return cell
        }
        return UICollectionViewCell()
    }
}

extension BooksController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
//        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20)
//    }
}

目标(类似于 collectionView 这里的东西)

类似的东西

我的输出

这是我的输出

标签: iosswiftuicollectionview

解决方案


如果您需要显示第二个集合视图单元格的一半,则可以使用

collectionView.contentInset = UIEdgeInsets.init(上:0,左:10,下:0,右:10)

对于高度和集合视图,您可以尝试 CollectionViewLayout 委托


推荐阅读