使用Storyboard + Auto Layout调整UICollectionView边界大小以适合单元格

时间:2018-05-30 22:24:45

标签: ios swift xcode uicollectionview

我在视图部分中有一个 UICollectionView ,并根据屏幕大小限制自动调整大小。

UICollectionView in Storyboard

我的 UICollectionView

的代码
let answerArray = ["ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", ".", "ABC", "AB", "AD", "."]
var cellMarginSize = 16

//MARK: - Data source Required Functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 40
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collection_View.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCell
    cell.setData(qNumber: indexPath.row + 1, qAnswer: answerArray[indexPath.row])
    return cell
}

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


//MARK: - Results IBs and Outlets
@IBOutlet weak var view_TopBar: UIView!
@IBOutlet weak var view_BottomBar: UIView!

@IBOutlet weak var label_SeriesName: UILabel!
@IBOutlet weak var label_SeriesDate: UILabel!

@IBOutlet weak var collection_View: UICollectionView!



//MARK: - Loading ---------------------------------------------------------------------
override func viewDidLoad() {
    super.viewDidLoad()

    //Collection View Delegates
    self.collection_View.isScrollEnabled = false
    self.collection_View.delegate = self
    self.collection_View.dataSource = self

    //Register the Cell
    self.collection_View.register(UINib(nibName: "ItemCell", bundle: nil), forCellWithReuseIdentifier: "ItemCell")

    //Setup GridView
    self.setupGridView()
}

//MARK: - Setup the Grid View
func setupGridView() {
    let flow = collection_View?.collectionViewLayout as! UICollectionViewFlowLayout
    flow.minimumInteritemSpacing = CGFloat(self.cellMarginSize)
    flow.minimumLineSpacing = CGFloat(self.cellMarginSize)
    //flow.collectionViewContentSize
}

正如你所看到的,我有一个固定数量的单元格(40)和一个固定单元格widht = 50和height = 20

这是我在运行应用程序时得到的结果:

Cells does not fit the dimensions of UICollectionView frame

我不想在UICollectionView中允许滚动/分页,所以我确实禁用了它们。

我想要实现的是让UICollectionView的框架/边界自动调整大小以适应所有单元格。

或换句话说,让所有单元格都适合UICollectionView的父视图,水平和垂直间距相等,无论父视图的高度和高度是什么(如android中的GridView)。

任何帮助都会非常感激! 谢谢。

0 个答案:

没有答案