CollectionView header doesn't resize on auto rotate

1.5k views Asked by At

I have a headerView in my CollectionView and have resized the headerView programmatically based on the text size of the Label. On rotating to landscape orientation the reusable header view doesn't resize automatically but on scrolling it resizes itself to give the intended result. In portrait mode In landscape mode before scrolling

In Landscape mode after scrolling

Below is the snippet I have used to resize my header.

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    switch kind{

    case UICollectionElementKindSectionHeader:

        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "HeaderView", forIndexPath: indexPath) as! CollectionViewHeader
        var headerString = westBeaches[indexPath.section] as NSString
        var newSize: CGSize = headerString.sizeWithAttributes([NSFontAttributeName:headerView.headerText.font])
        headerView.frame.size.width = newSize.width + 20
        headerView.layer.cornerRadius = 15
        headerView.headerText.text = westBeaches[indexPath.section]
        headerView.center.x = collectionView.center.x
        headerView.alpha = 0.7
        return headerView

    default:

        assert(false, "Unexpected element Kind")

    }

}

CollectionViewHeader is a custom class inheriting UIcollectionReusableView and contains headerText as UILabel. Is there any way to prevent the reusable view from going back to its original size when the orientation changes?

2

There are 2 answers

6
Vikas Pandey On

You have to update UICollectionView flow layout for orientations.

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {

    collectionView.performBatchUpdates({ () -> Void in

    }, completion: { (complete) -> Void in

    })

}
0
Ahmad Baraka On

For me I had a UISearchBar as a header, and had this same problem. That is after rotation the search bar doesn't fill the CollectionView width.

I fixed it by animating the search bar's width alongside the rotation animation.

In UIViewController

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    // Animate searchBar too
    coordinator.animateAlongsideTransition({ [unowned self] _ in
        var frame = self.searchController.searchBar.frame
        frame.size.width = size.width
        self.searchController.searchBar.frame = frame
        }, completion: nil)
}