gpt4 book ai didi

ios - UICollectionViewCell 高度基于标签大小

转载 作者:行者123 更新时间:2023-11-29 01:54:32 25 4
gpt4 key购买 nike

我有一个包含 UICollectionView 的 View ,它加载 UICollectionViewCell 的外部 cellnib 文件。我的数据按照我想要的方式正确显示。我想根据其中的文本标签保留单元格高度,但我不确定下面的代码中缺少什么。我尝试过查看答案,但对于如何解决它没有多大意义。请帮忙。提前致谢。

  - (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@" mycell" forIndexPath:indexPath];

NSString *string = cell.lblContact.text;
CGSize size = [self getLabelSize:string];
NSLog(@"%f and %f",size.width ,size.height);

return cell;
}

- (CGSize)getLabelSize:(NSString *)string {

UIFont *updatedFont = [UIFont fontWithName:@"myFont" size:18.0];
CGRect rect = [string boundingRectWithSize:(CGSize){maxWidth, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: updatedFont } context:nil];
return rect.size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize retval = CGSizeMake(collectionView.frame.size.width, 75);
return retval;
}

- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, 0, 0, 0);
}

最佳答案

我找到了解决方案。我在 sizeForItemAtIndexPath 中创建了一个字符串,它从与 cell.lblContact.text 相同的位置获取值。

MyObject *mc = (MyObject *) [contactArray objectAtIndex:indexPath.row];
NSString *myString = mc.contactName;
CGSize size = [self getLabelSize:myString];
NSLog(@"%@", myString);
NSLog(@"%f", size.height);

if (myString.length > 25) {
CGSize retval = CGSizeMake(collectionView.frame.size.width, size.height);
[collectionView layoutIfNeeded];
return retval;
} else {
CGSize retval = CGSizeMake(collectionView.frame.size.width, 75);
return retval;
}

关于ios - UICollectionViewCell 高度基于标签大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31027630/

25 4 0