2016-02-29 63 views
0

如何以編程方式設置UICollectionView的高度取決於它中有多少單元格?如何確定我需要爲UICollectionView設置的高度?

到目前爲止,這是我想的,

CGFloat cellHeight = 100; 
    CGFloat height = [imageFilesArray count] * cellHeight; 
    CGFloat width = self.view.bounds.size.width; 
    collectionView.frame = CGRectMake(0, 177, width, height); 

還當我這樣做,集合視圖的下半部分沒有響應didSelect

+0

請告訴我,您是從storyboard/xib添加的收藏視圖,並且您使用的是自動佈局嗎? –

+0

@BharatModi我以編程方式創建了我的collectionView。 – farhan

回答

1

可以計算集合的高度根據要顯示的項目數量進行查看。這是一個計算集合視圖高度的小函數。

此方法在一行中顯示兩個元素。你可以根據你的需要進行修改。

func calculateCollectionViewHeight(imageList:[AnyObject]) -> CGFloat { 
    if imageList.count <= 2 { 
     return 320 // if will set height to 320 if there is only two or less than 2 element in the list 
    } 
    if products.count % 2 == 0 { 
     return CGFloat(295 * (products.count/2)) // this will calculate the height of collection view if list is even 
    }else{ 
     return CGFloat(295 * (products.count/2 + 1)) // this will calculate the height of collection view if list is odd 
    } 

    } 

現在只需撥打

collectionView.frame.size.height = calculateCollectionViewHeight(tempArray) // list of objects 
+0

我應該在哪裏設置我的代碼的高度? WillDisplayCell? – farhan

+1

你可以在viewDidLoad中設置高度,或者在重新加載collectionView之前獲取你的清單 – ajaysinghmehra

+0

如果我有3列 – farhan

0
static int columns = 4; 

int yushu = self.dataSource.count%columns; 
int shang = (int)self.dataSource.count/columns; 
int lineNum = 0; 
if (yushu == 0) { 
    lineNum = shang; 
}else 
{ 
    lineNum = shang +1 ; 
} 
height = cellHeight*lineNum 

我的英語很差,我希望這能解決你的問題。

0

試試這個,它可以幫助你(我不知道因爲您正在以編程方式進行此操作)

//Get the height required for collectionView content 
CGFloat height = collectionView.contentSize.height; 

CGRect collectionViewFrame = collectionView.frame; 

//Update collectionView height 
collectionViewFrame.size.height = height; 

或者相反,我更喜歡使用自動佈局,如果您想使用VFL,也可以以編程方式設置約束。上述解決方案絕對適用於自動佈局。

相關問題