在UIView中调整CollectionViewCell的大小

时间:2016-11-07 13:25:56

标签: ios iphone swift xcode swift3

我在UIView中有CollectionView。如何将CollectionViewCell的大小调整为屏幕宽度的50%?我想在CollectionView中创建2列。

class Class_MyUIViewClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate 
{

此外,我在CollectionViewCell中有图像和标签。

2 个答案:

答案 0 :(得分:1)

您可以使用UICollectionView的sizeForItemAt方法来管理它的单元格大小

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let screenWidth = UIScreen.main.fixedCoordinateSpace.bounds.width
    return CGSize(width: screenWidth/2, height: yourHeight)
} 

同时确认UICollectionViewDelegateFlowLayout

答案 1 :(得分:0)

假设您知道所需的单元格高度,请符合UICollectionViewDelegateFlowLayout

class Class_MyUIViewClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

并实施sizeForItemAtIndexPath

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let desirednumberOfCollumns: CGFloat = 2
    let width = collectionView.frame.width / desirednumberOfCollumns
    return CGSize(width, yourHeight)
}
相关问题