ios – 基于设备尺寸的UICollectionView单元格间距

前端之家收集整理的这篇文章主要介绍了ios – 基于设备尺寸的UICollectionView单元格间距前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经实现了一个UICollectionView,单元格大小是w90 h90.当我在iPhone 6上运行它时,我得到了单元格之间的适当间距,但是当我在iPhone 5上做到这一点,我在单元格之间获得更多的间距.我的问题是我如何根据设备屏幕尺寸改变单元格大小,假设如果单元格大小是w80 h80,我在iPhone 5上得到正确的结果.我目前正在做的是
override func viewWillAppear(animated: Bool) {

        var scale = UIScreen.mainScreen().scale as CGFloat
        println("Scale :\(scale)")

        var cellSize = (self.collectionViewLayout as UICollectionViewFlowLayout).itemSize
        println("Cell size :\(cellSize)")

        imageSize = CGSizeMake(cellSize.width * scale,cellSize.height * scale)
        println("Image size : \(imageSize)")

    }

// sizeForItemAtIndexPath

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

        return imageSize!

   }

iPhone 6结果:

结果在iPhone 5s

Objective-C / Swift对于解决方案都很好.
谢谢.

解决方法

步骤1:实现UICollectionViewDelegateFlowLayout(如果没有完成).

步骤2:使用UICollectionViewDelegateFlowLayout的委托方法.

func collectionView(collectionView: UICollectionView,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return CGSizeMake((UIScreen.mainScreen().bounds.width-15)/4,120); //use height whatever you wants.
}

步骤3:转到XIB或StoryBoard,您拥有您的CollectionView.

步骤4:在XIB或StoryBoard中,您有CollectionView单击CollectionView.

步骤5:转到InterfaceBuilder,然后在最后一个选项卡(即:尺寸检查器)中设置最小间距

对于细胞= 5

对于线= 5

就这样

Note:

  • This solution is for if you wants to make spacing between cell = 5.
  • If your spacing is different then 5,then you need to change value 15 in delegate method.
  • Ex: Spacing between cell = 10,then change delegate 15 to 10×3 = 30

return CGSizeMake((UIScreen.mainScreen().bounds.width-30)/4,120);

>并设置最小间距

For Cells = 10

For Lines = 10

反之亦然.

Swift 3版本

func collectionView(_ collectionView: UICollectionView,sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = UIScreen.main.bounds.width
    return CGSize(width: (width - 10)/3,height: (width - 10)/3) // width & height are the same to make a square cell
}
原文链接:https://www.f2er.com/iOS/336455.html

猜你在找的iOS相关文章