我想根據單元格內容(特別是UILabel)的大小更改UICollectionViewCell的高度。我設置的UILabel高度UICollectionViewCell的設置高度
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewcellForItemAtIndexPath:(NSIndexPath *)indexPath
然後我設置UICollectionViewCell高度
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
它出現的第二個方法是在第一個調用之前,所以標籤的高度還沒有被計算。完整的代碼發現如下(警告:需要一個整潔!)。有任何想法嗎?
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *myCell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"Cell"
forIndexPath:indexPath];
label = [[UILabel alloc] initWithFrame:CGRectMake(80,10,width - 90,0)];
label.text = @"Hellfoneofinerigoneriognwirotngwtngowirnthointgonowenfkqejb fgjkreb glknrlegkn ewlj qerlgjnweofjpeorihgpireghiperhgorgrngl;rtnh;ltm;l";
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
label.font = [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:17];
[label sizeToFit];
[myCell.contentView addSubview:label];
CGSize labelY = [label bounds].size;
i = labelY.height;
NSLog(@"Height: %d", i);
return myCell;
}
#pragma mark <UICollectionViewDelegate>
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Height: %d", i);
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
CGSize result = [[UIScreen mainScreen] bounds].size;
if(result.height == 568)
{
return CGSizeMake(300.f, i);
}
if(result.height == 667)
{
return CGSizeMake(340.f, i);
}
if(result.height == 736)
{
return CGSizeMake(370.f, i);
}
}
return CGSizeMake(300.f, i);
}
編輯:沒有真正解釋錯誤。當調用-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath .
時,i的高度等於零。