Quantcast
Channel: Check if a UIScrollView reached the top or bottom - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by Alexander Dvornikov for Check if a UIScrollView reached the top or bottom

$
0
0

Well, contentInsets are also involved, when you try to determine whether scrollView is at the top or at the bottom. You might also be interested in cases when your scrollView is above the top and below the bottom. Here is the code I use to find top and bottom positions:

Swift:

extension UIScrollView {    var isAtTop: Bool {        return contentOffset.y <= verticalOffsetForTop    }    var isAtBottom: Bool {        return contentOffset.y >= verticalOffsetForBottom    }    var verticalOffsetForTop: CGFloat {        let topInset = contentInset.top        return -topInset    }    var verticalOffsetForBottom: CGFloat {        let scrollViewHeight = bounds.height        let scrollContentSizeHeight = contentSize.height        let bottomInset = contentInset.bottom        let scrollViewBottomOffset = scrollContentSizeHeight + bottomInset - scrollViewHeight        return scrollViewBottomOffset    }}

Objective-C:

@implementation UIScrollView (Additions)- (BOOL)isAtTop {    return (self.contentOffset.y <= [self verticalOffsetForTop]);}- (BOOL)isAtBottom {    return (self.contentOffset.y >= [self verticalOffsetForBottom]);}- (CGFloat)verticalOffsetForTop {    CGFloat topInset = self.contentInset.top;    return -topInset;}- (CGFloat)verticalOffsetForBottom {    CGFloat scrollViewHeight = self.bounds.size.height;    CGFloat scrollContentSizeHeight = self.contentSize.height;    CGFloat bottomInset = self.contentInset.bottom;    CGFloat scrollViewBottomOffset = scrollContentSizeHeight + bottomInset - scrollViewHeight;    return scrollViewBottomOffset;}@end

Viewing all articles
Browse latest Browse all 7

Trending Articles