我有一个包含UICollectionView的视图,它加载了UICollectionViewCell的外部cellnib文件。我的数据正确地显示了我想要的方式。我想根据其中的textlabel保持单元格高度,但我不确定在下面的代码中我缺少什么。我试过通过答案,但对如何解决它没有多大意义。请帮忙。提前谢谢。
- (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);
}
答案 0 :(得分:1)
我找到了解决方案。我在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;
}
答案 1 :(得分:0)
您检索标签的大小,但看起来您使用不同的CGSize来标记标签大小。而不是CGSizeMake(collectionView.frame.size.width, 75)
,请尝试保留对标签大小的引用,并将其用作返回值:
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@" mycell" forIndexPath:indexPath];
NSString *string = cell.lblContact.text;
self.labelSize = [self getLabelSize:string];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.labelSize;
}
修改强>
您是否尝试过访问标签的框架并进行存储?
self.labelSize = CGSizeMake(self.myCell.frame.size.width, self.myCell.frame.size.height);