ios - AutoLayout - 将 UILabel 的大小调整到它的 Superview 并调整它的大小

标签 ios ios6 uilabel uicollectionview autolayout

我有一个包含一些单元格的 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/

相关文章:

ios - 如何在UITableViewCell中设置动态标签大小

iOS - NSOperation 中的异步 NSURLConnection

ios - 在 SwiftUI 中呈现 NavigationLink 时过渡动画消失了

safari - 在 iOS 6 上的 Safari 上授权使用 JS 客户端 API 库时,是否可以支持多个 Google 帐户?

ios - 更改 UIImageView 大小以匹配图像与 AutoLayout

ios - 如何处理我的数据中的 NSNull?

objective-c - 了解仪器和内存管理

ios - 在tableviewcell中显示视频的缩略图

ios - 什么时候 -[UITextInput selectionRectsForRange :] called?

iphone - UILabels 完整文本不可见