实际上我想动态设置按钮并且按钮的标题显示为动态我已经尝试过并获得动态内容的宽度但我没有设置单元格宽度和高度。
- (void)viewDidLoad {
[super viewDidLoad];
ContentArray = [[NSMutableArray alloc]init];
self.collectionview.delegate = self;
self.collectionview.dataSource =self;
self.collectionview.backgroundColor = [UIColor clearColor];
[ContentArray addObject:@"Planning"];
[ContentArray addObject:@"Resources"];
[ContentArray addObject:@"Human Resources"];
[ContentArray addObject:@"Agriculture"];
[ContentArray addObject:@"Resources management"];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return ContentArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell * Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell"forIndexPath:indexPath];
[Cell.button setTitle:[ContentArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
return Cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGRect rect = [[ContentArray objectAtIndex:indexPath.row ] boundingRectWithSize:CGSizeMake(HUGE_VALF, 50) options:NSStringDrawingUsesFontLeading attributes:nil context:nil] ;
return CGSizeMake(rect.size.width, 50);
}
输出是这样的
如果我让单元格动态宽度和高度,我认为这是完美的,所以请指导我完成这个。
最佳答案
编译指示标记 - GetHeightFromString
- (CGFloat)getTextHeightFromString:(NSString *)text ViewWidth:(CGFloat)width WithPading:(CGFloat)pading FontName:(NSString *)fontName AndFontSize:(CGFloat)fontSize
{
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:fontName size:fontSize]};
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
//NSLog(@"rect.size.height: %f", rect.size.height);
return rect.size.height + pading;
}
从此方法获取字符串的高度,并将其添加到您想要使用的单元格或标签或按钮的原始高度。
例如:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
YourCellClass *myCell = (YourCellClass*) [collectionView cellForItemAtIndexPath:indexPath];
CGFloat sizeFromString = [self getTextHeightFromString:itemObject.MenuDescription ViewWidth:myCell.frame.size.width WithPading:10 FontName:@"HelveticaNeue" AndFontSize:13];
return CGSizeMake(sizeFromString, sizeFromString);
}
您可能还需要更改内部标签的高度,为此请在 UICollectionView
的 cellForItemAtIndexPath
方法中使用相同的方法。
此外,您还可以自定义自己的方式。
关于ios - 设置 Collection View 单元格的动态宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38785870/