我正在尝试调整 CollectionView 中项目布局的大小以适应保持纵横比的屏幕大小。到目前为止它只在 iPad 上运行良好,我根据 Assets 的尺寸设置了高度和宽度:
private let CardWidth: CGFloat = 362
private let CardHeight: CGFloat = 568
然后在继承自UICollectionViewFlowDelegate
的CardLayout
类中:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
scrollDirection = UICollectionViewScrollDirection.Horizontal
itemSize = CGSizeMake(PageWidth, PageHeight)
minimumInteritemSpacing = 10
}
问题是项目是卡片,所以 height
> width
,而我只在横向上为 iPhone 和 iPad 开发,所以我尝试使用UIScreen.mainScreen().bounds
没有成功。我设法为 iPhone 和 iPad 添加 CollectionViewController
获得了不错的结果:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
retrun CGSizeMake(collectionView.frame.size.width / 2 ,collectionView.frame.size.height/ 2)
}
我在 return
中交换了 width
和 height
,因为该应用程序仅限横向。这仍然不是最好的解决方案,因为卡片不保持纵横比。那么有没有一种方法可以使尺寸适应屏幕以保持纵横比?
感谢您的帮助。
最佳答案
您可以将纵横比约束应用于单元格,以便它们自身保持纵横比,然后将来自单元格的另一个约束应用于 View ,以便它们保持相对于 View 的纵横比。然后,您可以应用等宽/等高约束,通过乘数调整单元格的大小。
关于swift - 根据保持纵横比 [Swift] 的屏幕尺寸调整 CollectionView 中项目布局的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228229/