【问题标题】:Fix UICollectionView cells in screen dynamically动态修复屏幕中的 UICollectionView 单元格
【发布时间】:2019-03-14 09:28:05
【问题描述】:

我正在开发一个 tvOS 应用程序,我想在不垂直或水平滚动的情况下修复电视屏幕中的所有单元格。这里的细胞计数将是动态的,这是主要问题。我想像这样设置所有单元格

例如: 如果细胞数为 4

如果单元格数为 5

如果单元格数为 9

如果单元格数为 11

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

我的代码是:

//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) 列和行。

【问题讨论】:

  • 如果计数是 15,你期望什么?
  • @Nikunj Kumbhani,实际上我只举了一个例子。我想要这样,因为 count 实际上是“n”
  • 很好,但是对于 15 岁及以上,您想要 5 X 3 还是 3 X 5?
  • @ Nikunj Kumbhani,列号的第一优先级是高度...我认为 4x4 更好
  • 所以这意味着超过 11 将是 4 X n 对吧?

标签: swift uicollectionview uicollectionviewcell tvos uicollectionviewflowlayout


【解决方案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)
        }
    }
}

来自故事板设置部分插图像这样。

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多