ios - Swift:collectionView 单元格

标签 ios swift uicollectionview nscollectionviewflowlayout

我创建了 collectionView 我有 3 个单元格。我希望我的单元格在所有设备的所有屏幕上看起来像这样:

enter image description here

但我在 iPad 上得到了这个结果。

enter image description here

如何解决?

更新

我在 UIViewController 中添加了 collectionView。我对 collectionView 有以下限制:

enter image description here

调整我的细胞大小:

enter image description here

代码:

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }

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

        return 3
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let itemsPerRow: CGFloat = 3
    let itemWidth = (collectionView.bounds.width / itemsPerRow)
    let itemHeight = itemWidth * 1.5
    return CGSize(width: itemWidth, height: itemHeight)
}

最佳答案

您需要自适应地更改单元格大小,否则该大小将不适用于所有屏幕尺寸。

您有自己的功能,您可以在其中返回单元格大小:

return CGSize(width: 182, height: 275)

相反,让它像这样自适应:

return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height)

或者,为了让中间有间隙,创建一个偏移量:

let offset = 10

let width = self.view.frame.width - offset * 4 // 4 gaps
let height = self.view.frame.height - offset * 2 // 2 gaps

return CGSize(width: width / 3, height: height) // Divide into equally-sized cells

当然,self.view 可以替换为您希望单元格适合的任何容器。

关于ios - Swift:collectionView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51121988/

相关文章:

ios - FMDB 阻止我的 UI

ios - Swift 中的 setObject 等价物

ios - 使用 ARKit 3.0 一次最多只能检测和跟踪 4 张图像

ios - 捏缩放后保持 collectionView 单元格位置

ios - 自其他 View 以来,如何更新 UITableViewController?

ios - 从 ARKit 获取特征点

ios - 在 ViewController 上保存数据(当移开或移至 ViewController 时)

ios - Swift 3 操纵 UICollectionViewCell 大小?

ios - 未在自定义 UICollectionViewLayout 上调用 viewForSupplementaryElementOfKind

ios - 在 Swift 中按契约(Contract)设计