Resize UICollectionViewCell on rotation - ios

I've got a UICollectionView that takes the whole of the screen. The UICollectionView has cells as big as the UICollectionView itself, and I use paging.
On rotation of the device I want the cells to adjust their size to the new UICollectionView size. I currently achieve this by interchanging a layout object in willAnimateRotationToInterfaceOrientation::
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
[_collectionView setCollectionViewLayout:[self collectionViewFlowLayoutForOrientation:toInterfaceOrientation] animated:YES];
}
with collectionViewFlowLayoutForOrientation: being as follows:
- (UICollectionViewFlowLayout *)collectionViewFlowLayoutForOrientation:(UIInterfaceOrientation)orientation
{
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat width = UIInterfaceOrientationIsLandscape(orientation) ? MAX(screenSize.width, screenSize.height) : MIN(screenSize.width, screenSize.height);
CGFloat height = UIInterfaceOrientationIsLandscape(orientation) ? MIN(screenSize.width, screenSize.height) : MAX(screenSize.width, screenSize.height);
UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[collectionViewFlowLayout setItemSize:CGSizeMake(width, height)];
[collectionViewFlowLayout setMinimumLineSpacing:0.0f];
[collectionViewFlowLayout setSectionInset:UIEdgeInsetsZero];
[collectionViewFlowLayout setMinimumInteritemSpacing:0.0f];
return collectionViewFlowLayout;
}
It doesn't work as intended.
First of all, I get a message in the console indicating I probably am doing something not entirely legitimate:
the behavior of the UICollectionViewFlowLayout is not defined because:
the item height must be less than the height of the UICollectionView minus the section insets top and bottom values.
It is a fair message, as starting the animation to rotate, the screen / UICollectionView still has the frame for the old orientation. I'd be inclined to abide it.
Secondly, the contentOffset is incorrect after rotation as it doesn't get recalculated.
I've seen other solutions which just invalidate the layout in willRotateToInterfaceOrientation:duration:, but this doesn't recalculate the contentOffset either. I followed it up by changing the contentOffset and contentSize as follows, but the result is not perfect either:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
CGSize fromCollectionViewSize = [self collectionViewSizeForOrientation:[self interfaceOrientation]];
CGSize toCollectionViewSize = [self collectionViewSizeForOrientation:toInterfaceOrientation];
CGFloat currentPage = [_collectionView contentOffset].x / [_collectionView bounds].size.width;
NSInteger itemCount = [_collectionView numberOfItemsInSection:0];
UICollectionViewFlowLayoutInvalidationContext *invalidationContext = [[UICollectionViewFlowLayoutInvalidationContext alloc] init];
[invalidationContext setContentSizeAdjustment:CGSizeMake((toCollectionViewSize.width - fromCollectionViewSize.width) * itemCount, toCollectionViewSize.height - fromCollectionViewSize.height)];
[invalidationContext setContentOffsetAdjustment:CGPointMake(currentPage * toCollectionViewSize.width - [_collectionView contentOffset].x, 0)];
[[_collectionView collectionViewLayout] invalidateLayoutWithContext:invalidationContext];
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
So, my question is: What solution gives the intended result?

Try adding the line
[_collectionView invalidateIntrinsicContentSize] just before you set your layout. This should cause it to re-calculate the layout, and, hopefully get rid of your warning message.

Related

UICollectionView Center Cells with paging enabled

Been trying to center align my cells using UICollectionView with paging enabled. Unfortunately I can never make the cells align in the center when trying to do this. As I scroll through the collection the cells always move slightly off. Im trying to achieve this for both Portrait and landscape views. Ive been using insets to try and center the cells and their position:
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){
return UIEdgeInsetsMake(50.0,inset,0.0,inset); // top, left, bottom, right
}
else{
return UIEdgeInsetsMake(50.0,inset,0.0,inset); // top, left, bottom, right
}
}
I then changed the line spacing:
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)
collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount-1) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
return inset;
}
else{
return inset;
}
The size of my cells are set here:
-(CGSize)
collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//Set Landscape size of cells
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-360;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-60;
NSLog(#"Is Landscape");
return CGSizeMake(cellWidth, cellHeigt);
}
//Set Potrait size of cells
else{
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-60;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-160;
NSLog(#"Is Portrait");
return CGSizeMake(cellWidth, cellHeigt);
}
}
Instead of trying to set the frame programmatically, you can simply set the the cell to occupy the whole width of the UICollectionView and center the content inside using autoLayout, this way you won't have to account for interface changes and different screen sizes as autoLayout will handle that for you. In your data source,
-(CGSize)
collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(collectionView.bounds.size.width, collectionView.bounds.size.height)
}
Set all your inter item spacing to 0 and enable paging for the UICollectionView
Next just use autoLayout to set the contents to center inside the cell!
Try This. you have to Take UICollectionViewFlowLayout and set it's scrolldirection,minimum space and attach to collection view Layout.
UICollectionViewFlowLayout *flowLayout;
- (void)viewDidLoad {
[super viewDidLoad];
flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.minimumInteritemSpacing = 0.0;
flowLayout.minimumLineSpacing = 0.0;
_obj_CollectionView.pagingEnabled = YES;
_obj_CollectionView.collectionViewLayout = flowLayout;
}
if you want to scroll vertically modify it.
Hope it will work.

How to find out the size of current iPhone screen to set the itemSize dynamically?

I need to make the cell in the collectionView as wide as the screen allows.
Apparently this should be reached by itemSize property.
In my example I have set the width to 400, but how can I set to to the width of the user's screen?
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.sectionInset = UIEdgeInsetsMake(10, 10, 9, 10);
layout.itemSize = CGSizeMake(400, 150);
self.collectionView = [[NewsSummaryCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
}
Rest of the code
UPDATE:
Still not wide enough, the next cell on right hand side can still be seen.
The collection layout has a reference to the collection view so you should use that to set the width of the items (and thus the cells). Setting the width to screen size may be larger than the collection so you don't want to do that. Also, you can set invalidation on bounds change so the layout knows if the items need to be updated.
I found it. Hope it helps someone else.
UIView *rootView = [[[UIApplication sharedApplication] keyWindow]
rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];
layout.itemSize = CGSizeMake(adjustedFrame.size.width, 150);

How can I resize a UICollectionViewCell along one axis without distorting its contents?

I am trying to resize a UICollectionViewCell along only one axis without distorting its contents.
I have read answers for similar problems involving UICollectionViewLayoutAttributes layoutAttributesForItemAtIndexPath and layoutAttributesForElementsInRect. I have also tried using initWithFrame and awakeFromNib in a UICollectionViewCell subclass. I have attempted to set UIViewContentMode to UIViewContentModeScaleAspectFit or UIViewContentModeScaleAspectFill in those methods, but that has had no effect.
So far, I still get distorted text when I stretch along only one axis.
So...
I have a UICollectionView with its cells defined in a xib. Currently the cell only contains a UILabel. The collection view uses UICollectionViewFlowLayout to do some minor customizations:
self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
[self.flowLayout setMinimumLineSpacing:1.0f];
[self.flowLayout setItemSize:CGSizeMake(self.cellSize.width, self.cellSize.height)];
[self.flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionView setCollectionViewLayout:self.flowLayout];
The UICollectionView is embedded inside a UIScrollView, and fits exactly inside the scroll view's dimensions. The scroll view size is set to be much larger than the screen in both directions. Hard-coded numbers are just for testing; I will turn them into appropriate constants later.
self.cellSize = CGSizeMake(150.0f, 150.0f);
CGSize scrollViewSize = self.scrollView.contentSize;
scrollViewSize.width = 20 * self.cellSize.width + 20.0f;
scrollViewSize.height = 20 * self.cellSize.height + 20.0f;
self.scrollView.contentSize = scrollViewSize;
self.collectionViewHeightConstraint.constant = self.scrollView.contentSize.height;
self.collectionViewWidthConstraint.constant = self.scrollView.contentSize.width;
The result is a grid which is scrollable in any direction. That part is working.
The grid needs to be stretchable, either proportionally or along only one axis at a time. I am using the following pinch gesture recognizer to make one-axis zooming happen (again, the hard-coded 1.0 value for y is just for testing):
- (IBAction)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
{
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, 1.0);
recognizer.scale = 1;
}
When I resize the collection view with a pinch gesture, the label in each cell stretches and deforms. Here's a screen grab:
(source: afterburnerimages.com)
I will supply any other pertinent information gladly, and all assistance is much appreciated!
Oky u are using scrollview which contains collection view then u can use scrollview delegate for zoom, in your case it is stretches, better u can use like below
for example,
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
_scrollView.delegate = self;
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setMinimumLineSpacing:1.0f];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[self.collectionVIew setCollectionViewLayout:flowLayout];
[self.collectionVIew registerClass:[CustomCollectionVIewCell class] forCellWithReuseIdentifier:#"CELL_ID"];
//setting up content size for scroll view
CGSize size = self.scrollView.contentSize;
size.width = 200 * 10;
size.height = 185 * 10;
self.scrollView.contentSize = size;
CGRect rect = CGRectZero;
rect.origin = self.scrollView.bounds.origin;
rect.size = size;
self.collectionVIew.frame = rect;
self.scrollView.backgroundColor = [UIColor greenColor];
[self.scrollView addSubview:self.collectionVIew];
[self.view addSubview:self.scrollView];
// CGRect scrollViewFrame = self.scrollView.frame;
// CGFloat scaleWidth = _collectionVIew.frame.size.width / self.scrollView.contentSize.width;
// CGFloat scaleHeight = _collectionVIew.frame.size.height / self.scrollView.contentSize.height;
// CGFloat minScale = MIN(scaleWidth, scaleHeight);
//set min scale must be less than max zoom scale so that it can be zoomable
self.scrollView.minimumZoomScale = 0.5;
self.scrollView.maximumZoomScale = 1.0f;
// self.scrollView.zoomScale = minScale; //default is 1.0f;
}
and use scroll view delegates to perform zoom
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.collectionVIew; //return collection view which is embedded inside scroll view
}
and result is something like gif below stretching proportionally without effecting the contents of collection view , hope this helps u .. :)

UITableView cell width on iOS 8 stuck at 320pt

I am currently trying to create a simple UITableView with custom cells without using storyboard.
I'm getting an issue on the iPhone 6 simulator where the table view has a width of 375 (as it should), but the cells inside are getting a width of 320.
The number 320 is nowhere to be found in the project as I am not hard coding it. When I am setting the background colour of the cell, it extends the full width of 375, but I need to align an image to the right, which only aligns 320 across as shown in the photo below.
I'm not sure if it's because I'm missing constraints or if there's a bug. Any help is appreciated, thanks!
Code to set up table:
- (TBMessageViewCell *)getMessageCellforTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"MessageCell";
TBMessageViewCell *cell = (TBMessageViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[TBMessageViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell createSubviews];
}
// Set the new message and refresh
[cell setMessage:self.viewModel.messages[indexPath.row]];
[cell populateSubviews];
cell.backgroundColor = [UIColor blueColor];
NSLog(#"cell Width: %f", cell.contentView.frame.size.width);
return cell;
}
Complete TBMessageViewCell:
#implementation TBMessageViewCell
const CGFloat MARGIN = 10.0f;
const CGFloat AVATAR_SIZE = 40.0f;
-(id)initWithStyle:(UITableViewCellStyle *)style reuseIdentifier:(NSString *)reuseIdentifier
{
if(self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]){
}
// Sets background and selected background color
self.backgroundColor = [UIColor clearColor];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor clearColor];
self.selectedBackgroundView = selectionColor;
return self;
}
- (void)populateSubviews
{
// Set the message body
[self.messageBodyLabel setText:self.message.body];
[self.messageBodyLabel setTextAlignment:NSTextAlignmentRight];
CGRect bodyFrame = CGRectMake(MARGIN, MARGIN, self.frame.size.width - (AVATAR_SIZE + (MARGIN * 3)), self.frame.size.height);
// Calculates the expected frame size based on the font and dimensions of the label
// FLT_MAX simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(bodyFrame.size.width, FLT_MAX);
CGRect textRect = [self.message.body boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:self.messageBodyLabel.font}
context:nil];
bodyFrame.size.height = textRect.size.height;
// Setup the new avatar frame (Right aligned)
CGRect avatarFrame = CGRectMake(bodyFrame.size.width + (MARGIN * 2), MARGIN, AVATAR_SIZE, AVATAR_SIZE);
// Align to the LEFT side for current user's messages
if ([[TBConfig userID] isEqualToString:self.message.user.userID]) {
// Set avatar to left if it's me
avatarFrame.origin.x = MARGIN;
bodyFrame.origin.x = AVATAR_SIZE + (MARGIN * 2);
[self.messageBodyLabel setTextAlignment:NSTextAlignmentLeft];
}
self.avatar.frame = avatarFrame;
self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2;
self.messageBodyLabel.frame = bodyFrame;
// Set the new cell height on the main Cell
CGFloat cellHeight = MAX(bodyFrame.size.height, self.frame.size.height) + MARGIN;
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, cellHeight);
// Set the new Profile avatar
if (![self.avatar.profileID isEqualToString:self.message.user.facebookID]) {
[self.avatar setProfileID:nil];
[self.avatar setProfileID:self.message.user.facebookID];
}
}
- (void)createSubviews
{
self.messageBodyLabel = [[UILabel alloc] init];
self.messageBodyLabel.textColor = [UIColor whiteColor];
self.messageBodyLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.messageBodyLabel.numberOfLines = 0;
[self addSubview:self.messageBodyLabel];
// Creates the avatar
self.avatar = [[FBProfilePictureView alloc] init];
[self.avatar setPictureCropping:FBProfilePictureCroppingSquare];
[self addSubview:self.avatar];
}
You're printing the size of the cell before it has been added to the display — before it has been sized. It doesn't yet know the size of tableview it will be added to.
The cells will be given an appropriate frame when added to the display.
EDIT: oh, and you probably don't want that cellIdentifier to be static. You probably wanted *const.
Don't know if you have found the answer. I faced the same problem when I was trying to subclass UITableViewCell and add custom subviews programmatically without using xib.
Finally the solution worked for me is to use [[UIScreen mainScreen] applicationFrame] instead of self.frame when calculating subviews' frames.
The proper way to solve this is to perform your layout in the layoutSubviews method.
In your case, simply call "populateSubviews" within "layoutSubviews" method, like this:
- (void)layoutSubviews {
[super layoutSubviews];
[self populateSubviews];
}
... but before doing this I would recommend that you do content population in a separate method (ie, calls to label.text = ...), and place all layout-affecting calls (ie, label.frame = ...) below [super layoutSubviews] in the method above.
That would result in something like:
- (void)layoutSubviews {
[super layoutSubviews];
CGRect bodyFrame = CGRectMake(MARGIN, MARGIN, self.frame.size.width - (AVATAR_SIZE + (MARGIN * 3)), self.frame.size.height);
// Calculates the expected frame size based on the font and dimensions of the label
// FLT_MAX simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(bodyFrame.size.width, FLT_MAX);
CGRect textRect = [self.message.body boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:self.messageBodyLabel.font}
context:nil];
bodyFrame.size.height = textRect.size.height;
// .. the rest of your layout code here ..
}
- (void)populateSubviews {
[self.messageBodyLabel setText:self.message.body];
// .. the rest of your code here ..
}
After you set your avatar frame in:
self.avatar.frame = avatarFrame;
self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2;
self.messageBodyLabel.frame = bodyFrame;
write
self.avatar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
It should hook your avatar image to the right margin and leave the left margin as flexible.
Select your table view cell's connection inspector and check if you haven't connected editingAccessoryView by mistake
While this answer may not be as straightforward as you'd expect UIKit to deliver, due to a bug in UITableView - when doing things programmatically - you gotta get your hands dirty. Xib lovers - be warned - this answer isn't for you. It's probably just working.
In later IOS versions, let's hope this problem get resolved. The problem is uitableview is hardcoding the dimensions of the cell to 320. In one project I had - I was forcing the frame size to to fix this. N.B. this has problems with splitview controller on iPad.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"cell frame width:%f",cell.frame.size.width); // you should see <- 320! WTH
// you can crudely correct this here
cell.frame = CGRectMake(0,0,[[UIScreen mainScreen] applicationFrame].size.width,CELL_HEIGHT);
}
Another option - that's working better for me is a local width variable to reference. I know this code is not ideal - but it works consistently.
#interface AbtractCustomCell : UITableViewCell {
float width;
}
#end
#implementation AbtractCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//optimise speed
// [self setOpaque:YES];
if ([SDiPhoneVersion deviceSize] == iPhone47inch) {
width = 375;
}
else if ([SDiPhoneVersion deviceSize] == iPhone47inch) {
width = 414;
}
else {
width = 320; // hardcode iphone 4/5 /ipad2
}
}
return self;
}
#end
then you have the option to make TBMessageViewCell a subclass of this AbstractCustomCell which will have this variable there for you. Instead of using self.contentView.bounds.size.width / self.bounds.size.width just use width.
I'm programmatically layout without Storyboard and facing same issue, and I need to return the cell upon cellForRowAt indexPath which in turn it still didnt manage to get the container size yet.
And I manage to solve it by move the layout codes into willDisplay cell delegate.

Keeping the contentOffset in a UICollectionView while rotating Interface Orientation

I'm trying to handle interface orientation changes in a UICollectionViewController. What I'm trying to achieve is, that I want to have the same contentOffset after an interface rotation. Meaning, that it should be changed corresponding to the ratio of the bounds change.
Starting in portrait with a content offset of {bounds.size.width * 2, 0} …
… should result to the content offset in landscape also with {bounds.size.width * 2, 0} (and vice versa).
Calculating the new offset is not the problem, but don't know, where (or when) to set it, to get a smooth animation. What I'm doing so fare is invalidating the layout in willRotateToInterfaceOrientation:duration: and resetting the content offset in didRotateFromInterfaceOrientation::
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration;
{
self.scrollPositionBeforeRotation = CGPointMake(self.collectionView.contentOffset.x / self.collectionView.contentSize.width,
self.collectionView.contentOffset.y / self.collectionView.contentSize.height);
[self.collectionView.collectionViewLayout invalidateLayout];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
{
CGPoint newContentOffset = CGPointMake(self.scrollPositionBeforeRotation.x * self.collectionView.contentSize.width,
self.scrollPositionBeforeRotation.y * self.collectionView.contentSize.height);
[self.collectionView newContentOffset animated:YES];
}
This changes the content offset after the rotation.
How can I set it during the rotation? I tried to set the new content offset in willAnimateRotationToInterfaceOrientation:duration: but this results into a very strange behavior.
An example can be found in my Project on GitHub.
You can either do this in the view controller:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard let collectionView = collectionView else { return }
let offset = collectionView.contentOffset
let width = collectionView.bounds.size.width
let index = round(offset.x / width)
let newOffset = CGPoint(x: index * size.width, y: offset.y)
coordinator.animate(alongsideTransition: { (context) in
collectionView.reloadData()
collectionView.setContentOffset(newOffset, animated: false)
}, completion: nil)
}
Or in the layout itself: https://stackoverflow.com/a/54868999/308315
Solution 1, "just snap"
If what you need is only to ensure that the contentOffset ends in a right position, you can create a subclass of UICollectionViewLayout and implement targetContentOffsetForProposedContentOffset: method. For example you could do something like this to calculate the page:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
{
NSInteger page = ceil(proposedContentOffset.x / [self.collectionView frame].size.width);
return CGPointMake(page * [self.collectionView frame].size.width, 0);
}
But the problem that you'll face is that the animation for that transition is extremely weird. What I'm doing on my case (which is almost the same as yours) is:
Solution 2, "smooth animation"
1) First I set the cell size, which can be managed by collectionView:layout:sizeForItemAtIndexPath: delegate method as follows:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return [self.view bounds].size;
}
Note that [self.view bounds] will change according to the device rotation.
2) When the device is about to rotate, I'm adding an imageView on top of the collection view with all resizing masks. This view will actually hide the collectionView weirdness (because it is on top of it) and since the willRotatoToInterfaceOrientation: method is called inside an animation block it will rotate accordingly. I'm also keeping the next contentOffset according to the shown indexPath so I can fix the contentOffset once the rotation is done:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
{
// Gets the first (and only) visible cell.
NSIndexPath *indexPath = [[self.collectionView indexPathsForVisibleItems] firstObject];
KSPhotoViewCell *cell = (id)[self.collectionView cellForItemAtIndexPath:indexPath];
// Creates a temporary imageView that will occupy the full screen and rotate.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[[cell imageView] image]];
[imageView setFrame:[self.view bounds]];
[imageView setTag:kTemporaryImageTag];
[imageView setBackgroundColor:[UIColor blackColor]];
[imageView setContentMode:[[cell imageView] contentMode]];
[imageView setAutoresizingMask:0xff];
[self.view insertSubview:imageView aboveSubview:self.collectionView];
// Invalidate layout and calculate (next) contentOffset.
contentOffsetAfterRotation = CGPointMake(indexPath.item * [self.view bounds].size.height, 0);
[[self.collectionView collectionViewLayout] invalidateLayout];
}
Note that my subclass of UICollectionViewCell has a public imageView property.
3) Finally, the last step is to "snap" the content offset to a valid page and remove the temporary imageview.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self.collectionView setContentOffset:contentOffsetAfterRotation];
[[self.view viewWithTag:kTemporaryImageTag] removeFromSuperview];
}
The "just snap" answer above didn't work for me as it frequently didn't end on the item that was in view before the rotate. So I derived a flow layout that uses a focus item (if set) for calculating the content offset. I set the item in willAnimateRotationToInterfaceOrientation and clear it in didRotateFromInterfaceOrientation. The inset adjustment seems to be need on IOS7 because the Collection view can layout under the top bar.
#interface HintedFlowLayout : UICollectionViewFlowLayout
#property (strong)NSIndexPath* pathForFocusItem;
#end
#implementation HintedFlowLayout
-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
{
if (self.pathForFocusItem) {
UICollectionViewLayoutAttributes* layoutAttrs = [self layoutAttributesForItemAtIndexPath:self.pathForFocusItem];
return CGPointMake(layoutAttrs.frame.origin.x - self.collectionView.contentInset.left, layoutAttrs.frame.origin.y-self.collectionView.contentInset.top);
}else{
return [super targetContentOffsetForProposedContentOffset:proposedContentOffset];
}
}
#end
Swift 4.2 subclass:
class RotatableCollectionViewFlowLayout: UICollectionViewFlowLayout {
private var focusedIndexPath: IndexPath?
override func prepare(forAnimatedBoundsChange oldBounds: CGRect) {
super.prepare(forAnimatedBoundsChange: oldBounds)
focusedIndexPath = collectionView?.indexPathsForVisibleItems.first
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard let indexPath = focusedIndexPath
, let attributes = layoutAttributesForItem(at: indexPath)
, let collectionView = collectionView else {
return super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
}
return CGPoint(x: attributes.frame.origin.x - collectionView.contentInset.left,
y: attributes.frame.origin.y - collectionView.contentInset.top)
}
override func finalizeAnimatedBoundsChange() {
super.finalizeAnimatedBoundsChange()
focusedIndexPath = nil
}
}
For those using iOS 8+, willRotateToInterfaceOrientation and didRotateFromInterfaceOrientation are deprecated.
You should use the following now:
/*
This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized).
If you override this method, you should either call super to propagate the change to children or manually forward the change to children.
*/
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Update scroll position during rotation animation
self.collectionView.contentOffset = (CGPoint){contentOffsetX, contentOffsetY};
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Whatever you want to do when the rotation animation is done
}];
}
Swift 3:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context:UIViewControllerTransitionCoordinatorContext) in
// Update scroll position during rotation animation
}) { (context:UIViewControllerTransitionCoordinatorContext) in
// Whatever you want to do when the rotation animation is done
}
}
I think the correct solution is to override targetContentOffsetForProposedContentOffset: method in a subclassed UICollectionViewFlowLayout
From the docs:
During layout updates, or when transitioning between layouts, the
collection view calls this method to give you the opportunity to
change the proposed content offset to use at the end of the animation.
You might override this method if the animations or transition might
cause items to be positioned in a way that is not optimal for your
design.
To piggy back off troppoli's solution you can set the offset in your custom class without having to worry about remembering to implement the code in your view controller. prepareForAnimatedBoundsChange should get called when you rotate the device then finalizeAnimatedBoundsChange after its done rotating.
#interface OrientationFlowLayout ()
#property (strong)NSIndexPath* pathForFocusItem;
#end
#implementation OrientationFlowLayout
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset {
if (self.pathForFocusItem) {
UICollectionViewLayoutAttributes* layoutAttrs = [self layoutAttributesForItemAtIndexPath:
self.pathForFocusItem];
return CGPointMake(layoutAttrs.frame.origin.x - self.collectionView.contentInset.left,
layoutAttrs.frame.origin.y - self.collectionView.contentInset.top);
}
else {
return [super targetContentOffsetForProposedContentOffset:proposedContentOffset];
}
}
- (void)prepareForAnimatedBoundsChange:(CGRect)oldBounds {
[super prepareForAnimatedBoundsChange:oldBounds];
self.pathForFocusItem = [[self.collectionView indexPathsForVisibleItems] firstObject];
}
- (void)finalizeAnimatedBoundsChange {
[super finalizeAnimatedBoundsChange];
self.pathForFocusItem = nil;
}
#end
This problem bothered me for a bit as well. The highest voted answered seemed a bit too hacky for me so I just dumbed it down a bit and just change the alpha of the collection view respectively before and after rotation. I also don't animate the content offset update.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
self.collectionView.alpha = 0;
[self.collectionView.collectionViewLayout invalidateLayout];
self.scrollPositionBeforeRotation = CGPointMake(self.collectionView.contentOffset.x / self.collectionView.contentSize.width,
self.collectionView.contentOffset.y / self.collectionView.contentSize.height);
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
{
CGPoint newContentOffset = CGPointMake(self.scrollPositionBeforeRotation.x * self.collectionView.contentSize.width,
self.scrollPositionBeforeRotation.y * self.collectionView.contentSize.height);
[self.collectionView setContentOffset:newContentOffset animated:NO];
self.collectionView.alpha = 1;
}
Fairly smooth and less hacky.
I use a variant of fz. answer (iOS 7 & 8) :
Before rotation :
Store the current visible index path
Create a snapshot of the collectionView
Put an UIImageView with it on top of the collection view
After rotation :
Scroll to the stored index
Remove the image view.
#property (nonatomic) NSIndexPath *indexPath;
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration {
self.indexPathAfterRotation = [[self.collectionView indexPathsForVisibleItems] firstObject];
// Creates a temporary imageView that will occupy the full screen and rotate.
UIGraphicsBeginImageContextWithOptions(self.collectionView.bounds.size, YES, 0);
[self.collectionView drawViewHierarchyInRect:self.collectionView.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setFrame:[self.collectionView bounds]];
[imageView setTag:kTemporaryImageTag];
[imageView setBackgroundColor:[UIColor blackColor]];
[imageView setContentMode:UIViewContentModeCenter];
[imageView setAutoresizingMask:0xff];
[self.view insertSubview:imageView aboveSubview:self.collectionView];
[[self.collectionView collectionViewLayout] invalidateLayout];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[self.collectionView scrollToItemAtIndexPath:self.indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
[[self.view viewWithTag:kTemporaryImageTag] removeFromSuperview];
}
After rotate interface orientation the UICollectionViewCell usually move to another position, because we won't update contentSize and contentOffset.
So the visible UICollectionViewCell always not locate at expected position.
The visible UICollectionView which we expected image as follow
Orientation which we expected
UICollectionView must delegate the function [collectionView sizeForItemAtIndexPath] of『UICollectionViewDelegateFlowLayout』.
And you should calculate the item Size in this function.
The custom UICollectionViewFlowLayout must override the functions as follow.
-(void)prepareLayout
. Set itemSize, scrollDirection and others.
-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
. Calculate page number or calculate visible content offset.
-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
. Return visual content offset.
-(CGSize)collectionViewContentSize
. Return the total content size of collectionView.
Your viewController must override 『willRotateToInterfaceOrientation』and in this function
you should call the function [XXXCollectionVew.collectionViewLayout invalidateLayout];
But 『willRotateToInterfaceOrientation』 is deprecated in iOS 9, or you could call the function [XXXCollectionVew.collectionViewLayout invalidateLayout] in difference way.
There's an example as follow :
https://github.com/bcbod2002/CollectionViewRotationTest
in Swift 3.
you should track which cell item(Page) is being presented before rotate by indexPath.item, the x coordinate or something else.
Then, in your UICollectionView:
override func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
let page:CGFloat = pageNumber // your tracked page number eg. 1.0
return CGPoint(x: page * collectionView.frame.size.width, y: -(topInset))
//the 'y' value would be '0' if you don't have any top EdgeInset
}
In my case I invalidate the layout in viewDidLayoutSubviews() so the collectionView.frame.size.width is the width of the collectionVC's view that has been rotated.
This work like a charm:
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.view.bounds.size;
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
int currentPage = collectionMedia.contentOffset.x / collectionMedia.bounds.size.width;
float width = collectionMedia.bounds.size.height;
[UIView animateWithDuration:duration animations:^{
[self.collectionMedia setContentOffset:CGPointMake(width * currentPage, 0.0) animated:NO];
[[self.collectionMedia collectionViewLayout] invalidateLayout];
}];
}
If found that using targetContentOffsetForProposedContentOffset does not work in all scenarios and the problem with using didRotateFromInterfaceOrientation is that it gives visual artifacts. My perfectly working code is as follows:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
_indexPathOfFirstCell = [self indexPathsForVisibleItems].firstObject;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
if (_indexPathOfFirstCell) {
[UIView performWithoutAnimation:^{
[self scrollToItemAtIndexPath:self->_indexPathOfFirstCell atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
}];
_indexPathOfFirstCell = nil;
}
}
The key is to use the willRotateToInterfaceOrientation method to determine the part in the view that you want to scroll to and willAnimationRotationToInterfaceOrientation to recalculate it when the view has changed its size (the bounds have already changed when this method is called by the framework) and to actually scroll to the new position without animation. In my code I used the index path for the first visual cell to do that, but a percentage of contentOffset.y/contentSize.height would also do the job in slightly different way.
What does the job for me is this:
Set the size of your my cells from your my UICollectionViewDelegateFlowLayout method
func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize
{
return collectionView.bounds.size
}
After that I implement willRotateToInterfaceOrientationToInterfaceOrientation:duration: like this
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval)
{
let currentPage = Int(collectionView.contentOffset.x / collectionView.bounds.size.width)
var width = collectionView.bounds.size.height
UIView.animateWithDuration(duration) {
self.collectionView.setContentOffset(CGPointMake(width * CGFloat(currentPage), 0.0), animated: false)
self.collectionView.collectionViewLayout.invalidateLayout()
}
}
The above code is in Swift but you get the point and it's easy to "translate"
You might want to hide the collectionView during it's (incorrect) animation and show a placeholder view of the cell that rotates correctly instead.
For a simple photo gallery I found a way to do it that looks quite good. See my answer here:
How to rotate a UICollectionView similar to the photos app and keep the current view centered?
My way is to use a UICollectionViewFlowlayout object.
Set the ojbect line spacing if it scrolls horizontally.
[flowLayout setMinimumLineSpacing:26.0f];
Set its interitem spacing if it scrolls vertically.
[flowLayout setMinimumInteritemSpacing:0.0f];
Notice it behaves different when you rotate the screen. In my case, I have it scrolls horizontally so minimumlinespacing is 26.0f. Then it seems horrible when it rotates to landscape direction. I have to check rotation and set minimumlinespacing for that direction 0.0f to make it right.
That's it! Simple.
I had the issue with my project,i used two different layout for the UICollectionView.
mCustomCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"LandScapeCell" forIndexPath:indexPath];
theCustomCell *cell = [cv dequeueReusableCellWithReuseIdentifier:#"PortraitCell" forIndexPath:indexPath];
Then Check it for each orientation and use your configuration for each orientation.
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize pnt = CGSizeMake(70, 70);
return pnt; }
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
// UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
return UIEdgeInsetsMake(3, 0, 3, 0); }
This way you can adjust the content offset and the size of your cell.
Use <CollectionViewDelegateFlowLayout> and in the method didRotateFromInterfaceOrientation: reload data of the CollectionView.
Implement collectionView:layout:sizeForItemAtIndexPath: method of <CollectionViewDelegateFlowLayout> and in the method verify the Interface orientation and apply your custom size of each cell.
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (UIInterfaceOrientationIsPortrait(orientation)) {
return CGSizeMake(CGFloat width, CGFloat height);
} else {
return CGSizeMake(CGFloat width, CGFloat height);
}
}
I have a similar case in which i use this
- (void)setFrame:(CGRect)frame
{
CGFloat currentWidth = [self frame].size.width;
CGFloat offsetModifier = [[self collectionView] contentOffset].x / currentWidth;
[super setFrame:frame];
CGFloat newWidth = [self frame].size.width;
[[self collectionView] setContentOffset:CGPointMake(offsetModifier * newWidth, 0.0f) animated:NO];
}
This is a view that contains a collectionView.
In the superview I also do this
- (void)setFrame:(CGRect)frame
{
UICollectionViewFlowLayout *collectionViewFlowLayout = (UICollectionViewFlowLayout *)[_collectionView collectionViewLayout];
[collectionViewFlowLayout setItemSize:frame.size];
[super setFrame:frame];
}
This is to adjust the cell sizes to be full screen (full view to be exact ;) ). If you do not do this here a lot of error messages may appear about that the cell size is bigger than the collectionview and that the behaviour for this is not defined and bla bla bla.....
These to methods can off course be merged into one subclass of the collectionview or in the view containing the collectionview but for my current project was this the logical way to go.
The "just snap" answer is the right approach and doesn't require extra smoothing with snapshot overlays IMO. However there's an issue which explains why some people see that the correct page isn't scrolled to in some cases. When calculating the page, you'd want to use the height and not the width. Why? Because the view geometry has already rotated by the time targetContentOffsetForProposedContentOffset is called, and so what was the width is now the height. Also rounding is more sensible than ceiling. So:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
{
NSInteger page = round(proposedContentOffset.x / self.collectionView.bounds.size.height);
return CGPointMake(page * self.collectionView.bounds.size.width, 0);
}
I solved this problem with Following Steps:
Calculate currently scrolled NSIndexPath
Disable Scrolling and Pagination in UICollectionView
Apply new Flow Layout to UICollectionView
Enable Scrolling and Pagination in UICollectionView
Scroll UICollectionView to current NSIndexPath
Here is the Code Template demonstrating the Above Steps:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration;
{
//Calculating Current IndexPath
CGRect visibleRect = (CGRect){.origin = self.yourCollectionView.contentOffset, .size = self.yourCollectionView.bounds.size};
CGPoint visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect));
self.currentIndexPath = [self.yourCollectionView indexPathForItemAtPoint:visiblePoint];
//Disable Scrolling and Pagination
[self disableScrolling];
//Applying New Flow Layout
[self setupNewFlowLayout];
//Enable Scrolling and Pagination
[self enableScrolling];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
{
//You can also call this at the End of `willRotate..` method.
//Scrolling UICollectionView to current Index Path
[self.yourCollectionView scrollToItemAtIndexPath:self.currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}
- (void) disableScrolling
{
self.yourCollectionView.scrollEnabled = false;
self.yourCollectionView.pagingEnabled = false;
}
- (void) enableScrolling
{
self.yourCollectionView.scrollEnabled = true;
self.yourCollectionView.pagingEnabled = true;
}
- (void) setupNewFlowLayout
{
UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
[flowLayout setItemSize:CGSizeMake(EXPECTED_WIDTH, EXPECTED_HEIGHT)];
[self.yourCollectionView setCollectionViewLayout:flowLayout animated:YES];
[self.yourCollectionView.collectionViewLayout invalidateLayout];
}
I hope this helps.
I had got some troubles with animateAlongsideTransition block in animateAlongsideTransition (see the code below).
Pay attention, that it is called during (but not before) the animation
My task was update the table view scroll position using scrolling to the top visible row (I’ve faced with the problem on iPad when table view cells shifted up when the device rotation, therefore I was founding the solution for that problem). But may be it would be useful for contentOffset too.
I tried to solve the problem by the following way:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
__weak TVChannelsListTableViewController *weakSelf = self;
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
weakSelf.topVisibleRowIndexPath = [[weakSelf.tableView indexPathsForVisibleRows] firstObject];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[weakSelf.tableView scrollToRowAtIndexPath:weakSelf.topVisibleRowIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}];
}
But it didn’t work. For instance, index path of the top cel was (0, 20). But when the device rotation animateAlongsideTransition block was called and [[weakSelf.tableView indexPathsForVisibleRows] firstObject] returned index path (0, 27).
I thought the problem was in retrieving index paths to weakSelf. Therefore to solve the problem I’ve moved self.topVisibleRowIndexPath before [coordinator animateAlongsideTransition: completion] method calling:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
__weak TVChannelsListTableViewController *weakSelf = self;
self.topVisibleRowIndexPath = [[weakSelf.tableView indexPathsForVisibleRows] firstObject];
[coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[weakSelf.tableView scrollToRowAtIndexPath:weakSelf.topVisibleRowIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}];
}
And the other interesting thing that I’ve discovered is that the deprecated methods willRotateToInterfaceOrientation and willRotateToInterfaceOrientation are still successful called in iOS later 8.0 when method viewWillTransitionToSize is not redefined.
So the other way to solve the problem in my case was to use deprecated method instead of new one. I think it would be not right solution, but it is possible to try if other ways don’t work :)
You might want to try this untested code:
- (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation
duration: (NSTimeInterval) duration
{
[UIView animateWithDuration: duration
animation: ^(void)
{
CGPoint newContentOffset = CGPointMake(self.scrollPositionBeforeRotation.x *
self.collectionView.contentSize.height,
self.scrollPositionBeforeRotation.y *
self.collectionView.contentSize.width);
[self.collectionView setContentOffset: newContentOffset
animated: YES];
}];
}

Resources