我有一个包含一些单元格的 UICollectionView
。
每个单元格中都有一个 UILabel
。标签内有一个字母,它充当一个磁贴(如此)。当更多单元格添加到 UICollectionView
时,UICollectionViewCells
的大小会发生以下变化:
-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
// NSLog(@"%s",__PRETTY_FUNCTION__);
NSLog(@"the word array count is: %i",self.wordArray.count);
if (self.wordArray.count <= 5) {
return CGSizeMake(50,50);
} else if (self.wordArray.count <= 6 ) {
return CGSizeMake(30, 30);
} else if (self.wordArray.count <= 8 ) {
return CGSizeMake(10, 10);
} else {
return CGSizeMake(100,100);
}
}
我现在要做的是在每次更改布局时重新调整单元格中 UILabel
的大小。如何使用 AutoLayout
使标签大小适合单元格大小?另外,如何根据 UILabel
大小更新字体大小?
最佳答案
您可以设置如下布局约束:
NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(label);
NSDictionary *insetMetrics = @{
@"left" : @(10.0f),
@"right" : @(10.0f),
@"top" : @(10.0f),
@"bottom" : @(10.0f)
};
[cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(left)-[label]-(right)-|" options:kNilOptions metrics:insetMetrics views:viewDictionary]];
[cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(top)-[label]-(bottom)-|" options:kNilOptions metrics:insetMetrics views:viewDictionary]];
如果您设置了正确的属性,UILabel 中的文本可以自动收缩(参见 UILabel Class Reference)。因此,如果您最初将字体大小设置为最大单元格所需的大小,随着标签缩小,文本也会随之缩小。
关于ios - AutoLayout - 将 UILabel 的大小调整到它的 Superview 并调整它的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18256525/