简体   繁体   中英

Dynamic Height for UICollectionView Cell

在此处输入图片说明 This is my first attempt at creating a collectionView programmatically. I used a couple tutorials to get where I am now which is a Facebook/LinkedIn-esque layout with a textView and imageView. They look great when there is an image but I have no idea how to make the cell dynamically smaller in height when there is no image. I know that I currently have a fixed height of 500 but it being my first attempt, I am not sure how to set it to dynamically adjust.

I've seen a lot of Obj-C examples but nothing (that I can understand) for Swift that I know how to implement.

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)
    }
}

My vertical visual layout constraints (created with an extension):

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

sizeForItemAtIndexPath is one of the collection view delegate function in which you can set the height of each cell. In this delegate just add a condition.. where you can check if the cell has an image or not and based on that set the height using CGSizeMake

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM