Last active
October 28, 2015 09:21
-
-
Save ryuheechul/ae3c1919238918aaa0dd to your computer and use it in GitHub Desktop.
When you want to keep the scroll position right when scroll view resizes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface UIScrollView (AdjustOffset) | |
- (CGFloat)updateContentOffsetWithPreviousHeight:(CGFloat)previousHeight distanceFromBottom:(CGFloat)distanceFromBottom; | |
@end | |
@implementation UIScrollView (AdjustOffset) | |
- (void)updateContentOffset:(CGPoint)offset | |
{ | |
self.contentOffset = [self adjustContentOffset:offset]; | |
} | |
- (CGPoint )adjustContentOffset:(CGPoint)offset | |
{ | |
if (offset.y < 0) { | |
offset.y = 0; | |
return offset; | |
} | |
else if (offset.y > self.contentSize.height - self.frame.size.height) { | |
offset.y = self.contentSize.height - self.frame.size.height; | |
return offset; | |
} | |
return offset; | |
} | |
- (CGFloat)offsetYWhenHeightResizedBiggerWithDistanceFromBottom:(CGFloat)distanceFromBottom | |
{ | |
CGFloat hiddenContentHeight = self.contentSize.height - self.frame.size.height; | |
return hiddenContentHeight - distanceFromBottom; | |
} | |
- (CGFloat)distanceFromBttomWithHeight:(CGFloat)height | |
{ | |
return self.contentSize.height - height - self.contentOffset.y; | |
} | |
- (CGFloat)updateContentOffsetWithPreviousHeight:(CGFloat)previousHeight distanceFromBottom:(CGFloat)distanceFromBottom | |
{ | |
CGPoint offset = self.contentOffset; | |
CGFloat diff = previousHeight - self.frame.size.height; | |
// update distanceFromBottom | |
if (diff >= 0) { | |
distanceFromBottom = [self distanceFromBttomWithHeight:previousHeight]; | |
} | |
[self updateContentOffset:({ | |
if (diff < 0) { // getting bigger | |
offset.y = [self offsetYWhenHeightResizedBiggerWithDistanceFromBottom:distanceFromBottom]; | |
} else { // getting smaller | |
offset.y += diff; | |
} | |
offset; | |
})]; | |
return distanceFromBottom; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment