Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Last active October 28, 2015 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryuheechul/ae3c1919238918aaa0dd to your computer and use it in GitHub Desktop.
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.
@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