2015-09-14 166 views
4

我有一个集合View和每个collectionViewCell中的图像。我想只有3个单元对于任何给定的帧/屏幕尺寸。我如何实现这一点。我已经写了一些基于this postUICollectionViewCell根据屏幕/ FrameSize大小Swift

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

    let numberOfCell = 3 
    let cellWidth: CGFloat = [[UIScreen mainScreen].bounds].size.width/numberOfCell 
    return CGSizeMake(cellWidth, cellWidth) 
    } 

但它不工作,并给出错误。做这个的最好方式是什么。

回答

7

这是您的SWIFT代码:

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

    let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat 
    let cellWidth = UIScreen.mainScreen().bounds.size.width/numberOfCell 
    return CGSizeMake(cellWidth, cellWidth) 
} 

这里numberOfCell的类型必须是CGFloat因为UIScreen.mainScreen().bounds.size.width回报CGFloat值,所以如果你想将其与numberOfCell划分然后键入numberOfCell必须CGFloat因为你可以不要将CGFloatInt分开。

+1

...如果我会这样做,细胞之间就会有间隙......我不想要,我想要在所有屏幕和所有方向上水平和垂直5 px间隙。细胞的数量按照这个顺序增加和减少。你能帮忙吗? – Saty

+0

没有为我工作。 –

+0

不要忘记添加“UICollectionViewDelegateFlowLayout”,而添加委托类 - @JayprakashDubey –

6

这是斯威夫特3码,你有实现UICollectionViewDelegateFlowLayout

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat 
      let cellWidth = UIScreen.main.bounds.size.width/numberOfCell 
      return CGSize(width: cellWidth, height: cellWidth) 
} 
+0

不要忘记添加“UICollectionViewDelegateFlowLayout”,同时添加委托类 –

0

答案Swift3,Xcode中8固定horizantal间距:

与先前的所有回答的问题是,单元尺寸给定CGSizeMake(cellWidth,cellWidth)实际上将所有屏幕都留空,因此collectionView会尝试通过减少每行中的一个元素和不需要的额外间距来调整行/列间距。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
      let linespacing = 5   //spacing you want horizantally and vertically 
      let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat 
      let cellWidth = UIScreen.mainScreen().bounds.size.width/numberOfCell 
      return CGSizeMake(cellWidth - linespacing, cellWidth - linespacing) 
} 
相关问题