jiri.huml
jiri.huml

Reputation: 113

Resize UICollectionView after view transition

I've built detail view in Interface Builder showing informations and photos about some object. Because lenght of informations and number of photos will vary, all is nested in UIScrollView.

Photos are shown in UICollectionView, but I need to always show all contained photos, so I disabled scrolling and dynamically changing Height constraint of UICollectionView by this function (called when finishing rendering cells):

func resizePhotosCollectionView() {
    photosCollectionViewHeightConstraint.constant = photosCollectionView.collectionViewLayout.collectionViewContentSize()
}

It works great until this UICollectionView needs resize (typically by device orientation change). I am trying to use UIViewControllerTransitionCoordinator in function:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animateAlongsideTransition(nil) { context in
        self.resizePhotosCollectionView()
    }
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

but result is jerky because Height constraint changed after transition is complete.

Is there any way how to automatically resize UICollectionView after view transition? If not, how to animate Height constraint change during transition?

Using Xcode 6.1 for target IOS 8.

Upvotes: 0

Views: 1790

Answers (2)

linimin
linimin

Reputation: 6377

If I recall correctly, you need to layout the view immediately.

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animateAlongsideTransition(nil) { context in
        self.resizePhotosCollectionView()
        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()
    }
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}

Upvotes: 1

Mundi
Mundi

Reputation: 80271

Have you tried wrapping your constraint update into a view animation?

photosCollectionViewHeightConstraint.constant =
    photosCollectionView.collectionViewLayout.collectionViewContentSize()
photosCollectionView.setNeedsUpdateConstraints()

UIView.animateWithDuration(0.3, animations: { () -> Void in
    photosCollectionView.layoutIfNeeded()
})

Upvotes: 0

Related Questions