动态修复屏幕上的UICollectionView单元格

时间:2019-03-14 09:28:05

标签: swift uicollectionview uicollectionviewcell tvos uicollectionviewflowlayout

我正在使用tvOS应用程序,我想固定电视屏幕中的所有单元,而无需垂直或水平滚动。在这里,细胞计数将是动态的,这是主要问题。我要像这样设置所有单元格

例如: 如果单元格计数为4

enter image description here

如果单元格计数为5

enter image description here

如果单元格计数为9

enter image description here

如果单元格计数为11

enter image description here

这里需要动态设置列和行以及单元格的高度和宽度。(不允许滚动)

我的代码是:

//Example array
var collectionViewArray:[UIColor] = [.brown, .red, .purple, .lightGray, .yellow, .black, .cyan, .magenta, .orange, .purple, .lightGray]

override func viewDidAppear(_ animated: Bool) {
    myCollectionView.delegate = self
    myCollectionView.dataSource = self

}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TVMenuCollectionViewCell
    cell.cellView.backgroundColor = collectionViewArray[indexPath.row]
 return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let screenWidth = collectionView.bounds.width
    let screenHeight = collectionView.bounds.height
 return CGSize(width: (screenWidth-50)/4, height: (screenHeight-40)/3)
}

实际上,如果单元格数量更多,我需要N x(N-1)个列和行。

1 个答案:

答案 0 :(得分:1)

工作代码Swift 4

您需要使用 UICollectionViewDelegateFlowLayout 这样的方法

class CardListViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

    // UICollectionViewDelegateFlowLayout Delegate method

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let screenWidth = collectionView.bounds.width
        let screenHeight = collectionView.bounds.height

        if 0 ... 4 ~= collectionViewArray.count{
           return CGSize(width: (screenWidth - 30) / 2, height: (screenHeight - 30) / 2)
        }else if 5 ... 9 ~= collectionViewArray.count{
            return CGSize(width: (screenWidth - 40) / 3, height: (screenHeight - 40) / 2)
        }else{
            return CGSize(width: (screenWidth - 50) / 4, height: (screenHeight - 50) / 2)
        }
    }
}

从“情节提要”集的节插入像这样。

Does Cloud Functions for Firebase support file operation?

输出

enter image description here