UICollectionView单元格间距基于设备屏幕大小

时间:2022-11-11 12:06:59

I have implemented a UICollectionView, the cell size is w90 h90. When i run it on iPhone 6 i get the proper spacing between cell but when i do it on iPhone 5s i get more spacing between cell. My question is how do i change cell size based on the device screen size, suppose if the cell size was w80 h80 i get proper results on iPhone 5s too. what I'm presently doing is

我已经实现了一个UICollectionView,单元格大小为w90 h90。当我在iPhone 6上运行时,我得到了单元格之间的适当间距,但是当我在iPhone 5s上运行时,我在单元格之间获得了更多的间距。我的问题是如何根据设备屏幕大小更改单元格大小,假设单元格大小为w80 h80,我也可以在iPhone 5s上获得正确的结果。我现在正在做的是

 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

// sizeForItemAtIndexPath

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

        return imageSize!

   }

Result on iPhone 6 : UICollectionView单元格间距基于设备屏幕大小

iPhone 6上的结果:

Result on iPhone 5s UICollectionView单元格间距基于设备屏幕大小

iPhone 5s的结果

Objective-C / Swift both fine for solution. Thanks.

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

5 个解决方案

#1


35  

Step 1: Implement UICollectionViewDelegateFlowLayout(if not done).

第1步:实现UICollectionViewDelegateFlowLayout(如果没有完成)。

Step 2: Use delegate method of UICollectionViewDelegateFlowLayout.

第2步:使用UICollectionViewDelegateFlowLayout的委托方法。

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

Step 3: Go to XIB or StoryBoard where you have your CollectionView.

第3步:转到您拥有CollectionView的XIB或StoryBoard。

Step 4: In XIB or StoryBoard where you have your CollectionView click on CollectionView.

第4步:在您拥有CollectionView的XIB或StoryBoard中,单击CollectionView。

Step 5: Go to InterfaceBuilder, then in second last tab (ie: Size Inspector) set Min Spacing

步骤5:转到InterfaceBuilder,然后在倒数第二个选项卡(即:Size Inspector)中设置Min Spacing

For Cells = 5

对于Cells = 5

For Lines = 5

对于Lines = 5

That it.

那就是它。

Note:

注意:

  • This solution is for if you wants to make spacing between cell = 5.
  • 如果您想在cell = 5之间建立间距,则可以使用此解决方案。
  • If your spacing is different then 5, then you need to change value 15 in delegate method.
  • 如果您的间距不同于5,那么您需要在委托方法中更改值15。
  • Ex: Spacing between cell = 10, then change delegate 15 to 10x3 = 30
  • 例如:单元格之间的间距= 10,然后将代理15更改为10x3 = 30

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

返回CGSizeMake((UIScreen.mainScreen()。bounds.width-30)/ 4,120);

  • And set Min Spacing
  • 并设置Min Spacing

For Cells = 10

对于Cells = 10

For Lines = 10

对于Lines = 10

and vice versa.

反之亦然。

Swift 3 Version

Swift 3版本

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, 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
}

#2


14  

For a slightly more flexible answer

有一个稍微灵活的答案

Allows you to adjust number of columns and spacing, expanding on Zaid Pathan's answer

允许您调整列数和间距,扩展Zaid Pathan的答案

// MARK: UICollectionViewDelegateFlowLayout delegate method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    let cellSpacing = CGFloat(2) //Define the space between each cell
    let leftRightMargin = CGFloat(20) //If defined in Interface Builder for "Section Insets"
    let numColumns = CGFloat(3) //The total number of columns you want

    let totalCellSpace = cellSpacing * (numColumns - 1)
    let screenWidth = UIScreen.mainScreen().bounds.width
    let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns
    let height = CGFloat(110) //whatever height you want

    return CGSizeMake(width, height);
}

#3


1  

I wanted 3 item in a section in Both IPad and iPhone. I worked out using the following code. Hope it helps!

1 ) Implement UICollectionViewDelegateFlowLayout delegate


2 )  var device = UIDevice.currentDevice().model

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        if (device == "iPad" || device == "iPad Simulator")
        {
            return CGSizeMake((UIScreen.mainScreen().bounds.width-15)/3,230)
        }
        return CGSizeMake((UIScreen.mainScreen().bounds.width-10)/3,120)
    }

#4


1  

Objective-c example:

Objective-c示例:

use this function

使用此功能

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
     return CGSizeMake(Your desired width, Your desired height);    
    // example: return CGSizeMake(self.view.frame.size.width-20, 100.f);
}

#5


0  

To expand on Tim's answer, there is a small caveat relating to partial point widths: Rounding of partial point widths might cause the width to be wider than will allow the number of desired columns. One way to work around this is to truncate the width using trunc():

为了扩展Tim的答案,关于部分点宽度有一个小警告:部分点宽度的舍入可能导致宽度比允许所需列数更宽。解决此问题的一种方法是使用trunc()截断宽度:

 return CGSizeMake(trunc(width), height)

#1


35  

Step 1: Implement UICollectionViewDelegateFlowLayout(if not done).

第1步:实现UICollectionViewDelegateFlowLayout(如果没有完成)。

Step 2: Use delegate method of UICollectionViewDelegateFlowLayout.

第2步:使用UICollectionViewDelegateFlowLayout的委托方法。

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

Step 3: Go to XIB or StoryBoard where you have your CollectionView.

第3步:转到您拥有CollectionView的XIB或StoryBoard。

Step 4: In XIB or StoryBoard where you have your CollectionView click on CollectionView.

第4步:在您拥有CollectionView的XIB或StoryBoard中,单击CollectionView。

Step 5: Go to InterfaceBuilder, then in second last tab (ie: Size Inspector) set Min Spacing

步骤5:转到InterfaceBuilder,然后在倒数第二个选项卡(即:Size Inspector)中设置Min Spacing

For Cells = 5

对于Cells = 5

For Lines = 5

对于Lines = 5

That it.

那就是它。

Note:

注意:

  • This solution is for if you wants to make spacing between cell = 5.
  • 如果您想在cell = 5之间建立间距,则可以使用此解决方案。
  • If your spacing is different then 5, then you need to change value 15 in delegate method.
  • 如果您的间距不同于5,那么您需要在委托方法中更改值15。
  • Ex: Spacing between cell = 10, then change delegate 15 to 10x3 = 30
  • 例如:单元格之间的间距= 10,然后将代理15更改为10x3 = 30

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

返回CGSizeMake((UIScreen.mainScreen()。bounds.width-30)/ 4,120);

  • And set Min Spacing
  • 并设置Min Spacing

For Cells = 10

对于Cells = 10

For Lines = 10

对于Lines = 10

and vice versa.

反之亦然。

Swift 3 Version

Swift 3版本

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, 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
}

#2


14  

For a slightly more flexible answer

有一个稍微灵活的答案

Allows you to adjust number of columns and spacing, expanding on Zaid Pathan's answer

允许您调整列数和间距,扩展Zaid Pathan的答案

// MARK: UICollectionViewDelegateFlowLayout delegate method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    let cellSpacing = CGFloat(2) //Define the space between each cell
    let leftRightMargin = CGFloat(20) //If defined in Interface Builder for "Section Insets"
    let numColumns = CGFloat(3) //The total number of columns you want

    let totalCellSpace = cellSpacing * (numColumns - 1)
    let screenWidth = UIScreen.mainScreen().bounds.width
    let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns
    let height = CGFloat(110) //whatever height you want

    return CGSizeMake(width, height);
}

#3


1  

I wanted 3 item in a section in Both IPad and iPhone. I worked out using the following code. Hope it helps!

1 ) Implement UICollectionViewDelegateFlowLayout delegate


2 )  var device = UIDevice.currentDevice().model

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        if (device == "iPad" || device == "iPad Simulator")
        {
            return CGSizeMake((UIScreen.mainScreen().bounds.width-15)/3,230)
        }
        return CGSizeMake((UIScreen.mainScreen().bounds.width-10)/3,120)
    }

#4


1  

Objective-c example:

Objective-c示例:

use this function

使用此功能

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
     return CGSizeMake(Your desired width, Your desired height);    
    // example: return CGSizeMake(self.view.frame.size.width-20, 100.f);
}

#5


0  

To expand on Tim's answer, there is a small caveat relating to partial point widths: Rounding of partial point widths might cause the width to be wider than will allow the number of desired columns. One way to work around this is to truncate the width using trunc():

为了扩展Tim的答案,关于部分点宽度有一个小警告:部分点宽度的舍入可能导致宽度比允许所需列数更宽。解决此问题的一种方法是使用trunc()截断宽度:

 return CGSizeMake(trunc(width), height)