简体   繁体   中英

self-sizing collection view cells using swift not working

I'm trying to create a collection view with cells that can autosize. previously i had used sizeForItemAtIndexPath but could not get the cell height exactly right for a textView with attributedString. I've decided to abandon that approach and use the auto-sizing feature. I have found some information here but mostly with objective-C. I am only familiar with Swift. Even so, I have picked through it and it is still not working.

What I have done so far is to include the following code in my viewDidLoad:

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.estimatedItemSize = CGSize(
        width: self.view.frame.size.width, height: 100)
}

the cell width is showing correctly however all the cell heights are stuck at 100 regardless of the content.

Is there something else I need to do to allow the autosizing to kick in? I'm pretty sure my storyboard constraints are set up correctly.

In addition to setting the estimatedItemSize , you should also make sure that you are not providing an item size via a delegate or datasource method. The point of the self-sizing mechanism is that UIKit will use the estimated item size as its initial estimate, and then calculate the exact height based on the Auto Layout constraints you've configured on the cell's contentView. Also, you need a Base SDK of iOS 8 or later.

This repo reproduces Apple's example from the WWDC session where they introduced self-sizing cells.

One workaround might be to size the collectionView cells height and width in proportion to the screen size:

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

        let deviceSize = UIScreen.mainScreen().bounds.size
        //let cellSize = sqrt(Double(deviceSize.width * deviceSize.height) / (Double(33)))

        let cellWidth = ((deviceSize.width / 2) - 10)
        let cellHeight = (deviceSize.height / 4)

        return CGSize(width: cellWidth , height: cellHeight)
    }

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