2014-03-31 21 views
0

我正在處理一個基於從MySQL數據庫返回的數據填充5個項目的項目。我的問題是我需要根據返回的數據製作每個項目的圓形或方形。在collectionView中創建形狀cellForItemAtIndexPath - 目標C

當運行以下內容:創建一個正方形稱爲

UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init]; 
_collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout]; 
[_collectionView setDataSource:self]; 
[_collectionView setDelegate:self]; 

[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"]; 
[_collectionView setBackgroundColor:[UIColor whiteColor]]; 
CGRect frame = [_collectionView frame]; 
[_collectionView setFrame:CGRectMake(10, 
             5, 
             300, 
             frame.size.height - 100)]; 
[self.view addSubview:_collectionView]; 

..A自定義佈局。我的問題是我怎樣才能使它在單元格創建功能內的方形或圓形?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
.... do my creation of circle or square in here 
} 

,而不是在這裏:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{  
    return CGSizeMake(50, 50); 
} 

回答

2

你會繼承UICollectionViewCell,並把繪製代碼的子類裏面,drawRect:

一旦創建了實際的類,你做的東西用它像

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    MyCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier"; 
    // set custom properties here 
    return cell; 
} 
+0

能給我在哪裏打電話的例子嗎?我的意思是在我的單元格創建中,我將在哪裏查看「UICollectionViewCell」。 –

+0

編輯我的答案 – Dima

1

沒有必要讓所有瘋狂的d子類化任何東西。

  1. 將您的單元設計爲方形(默認)。
  2. 在sizeForRowAtIndex(我在我的手機中輸入,所以我不記得確切的名字),做你的邏輯知道什麼時候做一個圓圈。
  3. 當你需要做一個圓只是做cell.layer.cornerRadius = cell.frame.size.width/2; (這將使它成爲一個圓圈)。
  4. 否則,重新設置正方形(做與上面相同的操作,但將半徑設置爲0)。

這種方法將讓你的代碼的模塊化