UICollectionView`reloadData`导致UILabel行消失

时间:2016-01-22 15:28:37

标签: ios uicollectionview uilabel reloaddata

我在UILabel标题中有一个collectionView。标签设置为零线,自动换行和正确的前导/尾随/顶部空间约束。如果我不调用[collectionView reloadData],标签会正确扩展为包含两行以上的文本。调用reloadData后,标签将返回单行...第二行消失。

 - (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        header = (viewRollHeader *) [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.rollTitle.text = [self.roll objectForKey:@"title"];
        header.rollDescription.text = [self.roll objectForKey:@"info"];

        [header.cancelButton addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];

        return header;
   }
   return [UICollectionReusableView new];
}


- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        CGRect labelRect = [[self.roll objectForKey:@"title"]
                        boundingRectWithSize: header.rollTitle.frame.size
                        options:NSStringDrawingUsesLineFragmentOrigin
                        attributes:@{NSFontAttributeName : [UIFont fontWithName:@"Arial-BoldMT" size:32.0f]}
                        context:nil];
        return CGSizeMake([[UIScreen mainScreen]bounds].size.width, (174.0f + labelRect.size.height));
    }
    return CGSizeZero;
}

3 个答案:

答案 0 :(得分:0)

collectionView:viewForSupplementaryElementOfKind:atIndexPath:用于整个 collectionView的页眉或页脚,而collectionView:referenceSizeForHeaderInSection:用于特定部分的页眉collectionView

要确保标题的大小保持一致并尊重您的约束,一旦实例化了flowlayout,您需要调用[(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout setHeaderReferenceSize:CGSizeMake(width, height)]

答案 1 :(得分:0)

在配置每个单元格的委托方法中使用label setter属性。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
//add label property here
    return cell;
} 

重新加载后,再次调用此方法来配置标签。

答案 2 :(得分:0)

尝试将preferredMaxLayoutWidth设置为标签

self.label.preferredMaxLayoutWidth = 300;