ios - 调整单元格大小以适合所有屏幕?

标签 ios swift xcode uicollectionview

我正在尝试让我的应用适合所有屏幕尺寸,但我不知道该怎么做。是否可以根据屏幕调整单元格的大小?目前我只是按如下方式配置我的 UICollectionView:

 func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return fields.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! FieldDistributionCollectionViewCell


        cell.frame.size = CGSize(width: ?, height: ?)
        return cell
    }

有推荐的方法吗?还是需要判断手机的版本,手动设置大小?在较小的屏幕 (4, 4s) 上我只想要 2 列,但在 (5, 5s, 6, 6s) 上我想要 3 列。我基本上只希望像元大小适合正确的分辨率。

最佳答案

试试这个代码:

从 collectionView 的协议(protocol)中实现以下功能:

  // cell size
 func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

  // To get 1 column
 return CGSize(width: view.frame.size.width, height: view.frame.size.width)

 // To get 2 column
 //return CGSize(width: view.frame.size.width/2, height: view.frame.size.width/2)

 // To get 3 column
 // return CGSize(width: view.frame.size.width/3, height: view.frame.size.width/3)

 // Toget 4 column
 // return CGSize(width: view.frame.size.width/4, height: view.frame.size.width/4)
  }

...其中 View 是您 Controller 的( super ) View

 // inter-spacing

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}

// line-spacing

func collectionView(collectionView: UICollectionView, layout
    collectionViewLayout: UICollectionViewLayout,
    minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}

CollectionView布局原理。

enter image description here

关于ios - 调整单元格大小以适合所有屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40325327/

相关文章:

ios - 如何在iOS中重新加载 TableView Controller 中的数据?

ios - 应用程序崩溃并出现应用内购买错误

ios - 如何更改 Flutter 中的 ios 模拟器?

ios - UIActivityViewController为WhatsApp或Facebook选择了不同的文本

ios - Swift NSPredicate 字符串变量不返回数据

swift - 我正在尝试检测 ARKit SceneKit 中两个节点之间的接触

Swift - 获取当前在另一个应用程序中打开的文档的文件路径

ios - 如何在 Core Data 中查找具有空关系的实体?

ios - iOS UILabel 约束是否来自边距被破坏的代码?

xcode - 什么是 Xcode 的组织标识符?