gpt4 book ai didi

ios - 如何在 iOS 中动态更改 UICollectionView 单元格高度

转载 作者:可可西里 更新时间:2023-11-01 06:14:28 27 4
gpt4 key购买 nike

我正在创建 UICollectionView 以显示来自服务器的一些数据。但我必须根据文本大小动态设置单元格高度。我正在为 UICollectionView 创建自定义单元格。

在我的 ViewDidLoad 方法中检索 UICollectionView 单元格:

UINib *cellNib = [UINib nibWithNibName:@"Custom_CollectionViewCell" bundle:nil];
[self.noteBookmarkCollectinView registerNib:cellNib forCellWithReuseIdentifier:@"CustomCell"];

下面是 UICollectionView 的委托(delegate)方法:

 #pragma mark Collection view layout things

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return noteDetailsArr.count;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 4.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 4.0;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0,4,0,4); // top, left, bottom, right
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(154, 154); // This is my fixed Cell height

//Before I am trying this below code also, but its not working
return [(NSString*)[contentArr objectAtIndex:indexPath.row] sizeWithAttributes:NULL];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"CustomCell";

Custom_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.contentLbl.numberOfLines = 0;
cell.contentLbl.tag = indexPath.row;

cell.contentLbl.text = [contentArr objectAtIndex:indexPath.row];
[cell.contentLbl sizeToFit];

return cell;
}

我的结果是这样的:

enter image description here

注:绿色为单元格背景色,粉色为标签背景色。

当我滚动 CollectionView 时,我可以看到如下图,再次滚动后它变得完美(仅适用于最后一行)

enter image description here

如何根据文本动态设置单元格高度。请帮我。我从过去 1 周就被困住了。

最佳答案

希望对你有帮助

#pragma mark <UICollectionViewDelegate>
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

NSString * string = [self.array objectAtIndex:indexPath.row]


//CALCULATE text SIZE:
CGSize textSize = [string sizeWithAttributes:NULL];
return textSize;
}

关于ios - 如何在 iOS 中动态更改 UICollectionView 单元格高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203873/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com