【问题标题】:How to make 5* 8 collection view in swift 3.0 [closed]如何在 swift 3.0 中制作 5*8 集合视图 [关闭]
【发布时间】:2017-08-14 08:59:29
【问题描述】:

我想每次都创建一个 5*8 矩阵的 UICollectionView。 (表示 5 行和 8 列)适用于所有 iphone 屏幕。 而 Collectionview 约束是:

导致superview = 10

到 superview = 10

顶部到超级视图 = 90

从底部到超级视图 = 150

集合视图结果应该显示如下:

结果视图

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! NavigateCollectionViewCell

        cell.questionLbl.text = items[indexPath.row] as? String
        cell.backgroundColor = UIColor.cyan

        return cell
    }

    // MARK: - UICollectionViewDelegate protocol

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }

请帮忙解决这个问题。

【问题讨论】:

  • self.view.frame.size.width(带空格) / 5
  • 你尝试了什么?听起来您刚刚提出了规范,并且希望有人为您提供代码。
  • 如果您要发布代码,请尝试使其与问题相关。获取单元格和处理选择的方法与集合视图中单元格的布局无关,这就是您的问题。

标签: ios swift swift3 uicollectionview


【解决方案1】:

你可以用

创造欲望
let cellWidth : CGFloat = (self.view.frame.width - 20.0 - (5 * YOUR_CELLSPACING)) / 5.0
let cellHeight : CGFloat = (self.view.frame.height - 260.0 - (8 * LINE_Spacing)) / 8.0
let collectionViewLayout: UICollectionViewFlowLayout = (self.YOUR_COLLECTIONVIEW!.collectionViewLayout as! UICollectionViewFlowLayout)

collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)

collectionViewLayout.itemSize = CGSize(width: cellWidth , height:cellHeight)

这可能会导致不同的高度和视图。

如果你想让你的高度和宽度保持不变,那么你只需这样做

//UICollectioncell 与宽度类似

collectionViewLayout.itemSize = CGSize(width: cellWidth , height:cellWidth)

//高度

//UICollectioncell 与宽度类似

collectionViewLayout.itemSize = CGSize(width: cellHeight , height:cellHeight)

【讨论】:

    【解决方案2】:

    在您的 collectionView 代表中

    func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 8
        }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 5
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
            let cellWidth = (UIScreen.main.bounds.width - 20) / 5
            return CGSize(width: cellWidth, height: cellWidth);
        }
    

    除了 20 之外,您还可以从边距 + 单元格间距中给出总的前导值 + 尾随值。

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 2015-03-12
      • 2020-10-03
      • 2016-12-30
      • 1970-01-01
      相关资源
      最近更新 更多