[英]How to achieve Grid view using collection view cell swift ios
Please let me know How to make grid view like 2 cell per each column for portrait and 3 cell for landscape. 请让我知道如何制作网格视图,例如每列纵向为2个单元格,横向为3个单元格。 Using collection view custom cell without using pods or third party framework. 使用集合视图自定义单元格而不使用Pod或第三方框架。
Thanks in advance. 提前致谢。
you need to do like this 你需要这样
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let collectionViewSize = collectionView.frame.size.width
if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
{
return CGSizeMake(collectionViewSize/3, collectionViewSize/3)
}
else if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation))
{
return CGSizeMake(collectionViewSize/2, collectionViewSize/2)
}
return CGSizeZero
}
you also need to reload on orientation change 您还需要在方向更改时重新加载
NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)
func rotated()
{
collectionView.reloadData()
}
Note : Make sure you will confirm UICollectionViewDelegateFlowLayout
protocol 注意 :确保您将确认UICollectionViewDelegateFlowLayout
协议
I have answered similar question like this here . 我在这里已经回答过类似的问题。 I have even explained how to change the view to match your requirement. 我什至解释了如何根据您的要求更改视图。 In your case it might look something like this. 在您的情况下,它可能看起来像这样。
let orientation = UIApplication.sharedApplication().statusBarOrientation
if(orientation == .LandscapeLeft || orientation == .LandscapeRight)
{
return CGSizeMake((yourCollectionView.frame.size.width-10)/3, (yourCollectionView.frame.size.height-10)/3)
}
else{
return CGSizeMake((yourCollectionView.frame.size.width-5)/2, (yourCollectionView.frame.size.height-5)/2)
}
The deduction is the cell padding(which is 5 in my case). 推导是单元格填充(在我的情况下为5)。 If 3 cells, then 2 cell padding making total of 10 deduction and if 2 cells, then 1 cell padding making total of 5 deduction. 如果3个单元格,则2个单元格填充总计10演绎;如果2个单元格,则1个单元格填充总计5个演绎。 Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.