UICollectionView的dynamic单元格宽度取决于标签宽度

我有一个UICollectionView,从包含标签的可重用单元格加载单元格。 数组提供了该标签的内容。 我可以用sizeToFit轻松地根据内容宽度调整标签宽度。 但是我不能让细胞适应标签。

这是代码

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"]; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section{ return [arrayOfStats count]; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return CGSizeMake(??????????); } - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath]; cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]]; // make label width depend on text width [cell.myLabel sizeToFit]; //get the width and height of the label (CGSize contains two parameters: width and height) CGSize labelSize = cell.myLbale.frame.size; NSLog(@"\n width = %f height = %f", labelSize.width,labelSize.height); return cell; } 

sizeForItemAtIndexPath返回文本的大小

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return [(NSString*)[arrayOfStats objectAtIndex:indexPath.row] sizeWithAttributes:NULL]; } 

签下面的代码,你可能会给CGSize很短。

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ NSString *testString = @"SOME TEXT"; CGSize calCulateSizze =[testString sizeWithAttributes:NULL]; calCulateSizze.width = calCulateSizze.width; calCulateSizze.height = calCulateSizze.height; return calCulateSizze; } 

在Swift 3

 let size = (arrayOfStats[indexPath.row] as NSString).size(attributes: nil)