当Collection View位于TableView单元格内时,如何为Collection View单元格的contentView设置动态高度?

时间:2017-06-28 14:29:23

标签: ios uitableview uicollectionview uicollectionviewcell uicollectionviewlayout

CollectionView内有TableViewCell。集合视图配置为具有水平滚动方向,一行包含2个项目。

我希望这些项目具有相同的宽度,并且一起占据整个TableViewCell的宽度,单元格之间的间距为5像素。我可以使用TableViewCell中的以下代码来获取此内容。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    int collectionViewWidth = self.contentView.frame.size.width;
    return CGSizeMake(collectionViewWidth/2 - 2.5, (CGRectGetHeight(collectionView.frame)));
}

集合视图单元格只有一个标签。但是,此标签包含的文本长度可能不同,最终可能会有多行。我想知道如何实现这一目标。

我已将故事板中标签的行数设置为0。从我有这个表视图的控制器,我在viewDidLoad -

中设置了以下内容
self.tableView.estimatedRowHeight = 210.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

heightForRowAtIndexPath方法中,我有 -

return UITableViewAutomaticDimension;

到目前为止,我尝试在CollectionViewCell中添加以下代码,但这没有帮助 -

- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {

    UICollectionViewLayoutAttributes *attr = [super preferredLayoutAttributesFittingAttributes:layoutAttributes]; //Must be called
    CGRect frame = attr.frame;
    frame.size.height = layoutAttributes.size.height; //Key here
    attr.frame = frame;
    return attr;
}

我不确定在这里需要做些什么来实现我想要的目标。

添加预期内容的快照。

enter image description here

0 个答案:

没有答案
相关问题