UICollectionView单元的动态高度

时间:2016-05-25 03:53:58

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

enter image description here 这是我第一次尝试以编程方式创建collectionView。我使用了几个教程来获取我现在的位置,这是一个带有textView和imageView的Facebook / LinkedIn风格的布局。当有图像时它们看起来很棒但我不知道如何在没有图像的情况下使单元格动态地变小。我知道我目前的固定高度为500,但这是我的第一次尝试,我不知道如何将其设置为动态调整。

我已经看过很多Obj-C示例,但是我知道如何实现Swift没有(我能理解)。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        if let textContent = dataSource.posts[indexPath.item].textContent {
            let rect = NSString(string: textContent).boundingRectWithSize(CGSizeMake(view.frame.width, 1000), options: NSStringDrawingOptions.UsesFontLeading.union(NSStringDrawingOptions.UsesLineFragmentOrigin), attributes: [NSFontAttributeName:UIFont.systemFontOfSize(14)], context: nil)

            return CGSizeMake(view.frame.width, rect.height + 370)
        }

        return CGSizeMake(view.frame.width, 500)
    }
}

我的垂直视觉布局约束(使用扩展名创建):

 addContstraintsWithFormat("V:|-8-[v0(44)]-4-[v1]-4-[v2][v3(44)][v4(1)][v5(44)]|", views: profileImg, postTextView, postImageView, likesCommentsLabel, dividerLineView, likeButton)

1 个答案:

答案 0 :(得分:0)

sizeForItemAtIndexPath 是集合视图委托功能之一,您可以在其中设置每个单元格的高度。在此委托中,只需添加条件..您可以在其中检查单元格是否有图像,并根据该设置高度使用 CGSizeMake

相关问题