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
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...