Swift中集合视图的横向 [英] Landscape orientation for Collection View in Swift
问题描述
我的收藏夹视图单元在横向方向上遇到问题.当应用程序为纵向模式时,它为我提供了每行正确的单元格数,即2.但是当我旋转应用程序以横向显示时,它每行显示1个单元格.这是我得到的屏幕:
I am encountering a problem on landscape orientation for my collection view cell. When the app is in portrait it gives me the correct number of cell per row which is 2. But when I rotate my app to landscape it display 1 cell per row. Here's the screen of what I got:
肖像:
风景:
这是我添加单元格大小的代码:
Here's my code for adding the size of the cell:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var screenSize = CGFloat()
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
screenSize = UIScreen.mainScreen().bounds.size.width
}
else {
screenSize = UIScreen.mainScreen().bounds.size.width
}
let cellWidth = screenSize / 2.0
return CGSizeMake(cellWidth, cellWidth)
}
推荐答案
这是您可以做的
let orientation = UIApplication.sharedApplication().statusBarOrientation
if(orientation == .LandscapeLeft || orientation == .LandscapeRight)
{
return CGSizeMake((yourCollectionView.frame.size.width-10)/2, (yourCollectionView.frame.size.height-10)/2)
}
else{
return CGSizeMake((yourCollectionView.frame.size.width-5)/2, (yourCollectionView.frame.size.height-10)/3)
}
此代码实现的功能:-如果您的视图是纵向的,则将看到2列和3行;如果您的视图是横向的,则将看到3列和2行.您在代码中看到的推论是两个连续单元格之间的间距.因此,如果有3列,则扣减为15;如果有2列,则扣减为10,假设两个单元格之间的间距为5.
What this code achieves:- If your view is in portrait you will see 2 column and 3 row and if your view is in landscape you will see 3 columns and 2 row. The deduction you see in the code is the spacing between two consecutive cells. So if there is 3 column the deduction is 15 and if there is 2 column the deduction is 10 assuming that the spacing between two cell is 5. Same goes for the row.
如果需要,您也可以使用屏幕尺寸,但是我在集合视图中具有自动布局约束以匹配屏幕尺寸,因此结果相同.我希望这就是您想要的.
You can use the screen size as well if you want but I had auto layout constraints in my collection view to match the size of the screen so it resulted the same. I hope this is what you were looking for.
这篇关于Swift中集合视图的横向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!