In general we use UIScrollView, UITableView or UICollectionView
& sometimes we have to scroll programmatically to Top or bottom, so we can achieve it by using setContentOffset
where we set where exactly to scroll
Below are 4 helper methods which help in scrolling the Scroll view
- UIScrollView scroll to bottom
- UIScrollView scroll to Top
- UIScrollView scroll to Right
- UIScrollView scroll to Left
//MARK: - Scrolling UIScrollView to possible 4 directions..
extension UIScrollView {
func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.height + self.contentInset.bottom)
self.setContentOffset(bottomOffset, animated: true)
}
func scrollToTop() {
let topOffset = CGPoint.zero
self.setContentOffset(topOffset, animated: true)
}
func scrollToRightEnd(animated: Bool) {
if self.contentSize.width < self.bounds.size.width { return }
let rightOffset = CGPoint(x: self.contentSize.width - self.bounds.size.width, y: 0)
self.setContentOffset(rightOffset, animated: animated)
}
func scrollToLeftEnd(animated: Bool) {
if self.contentSize.width < self.bounds.size.width { return }
let leftOffset = CGPoint.zero
self.setContentOffset(leftOffset, animated: animated)
}
}
Example Usage :
DispatchQueue.main.async {
self.itemsScrollView.scrollToTop()
}
You can Test on This ScrollView project:
Please consider adjustedContentInset, which will be more accurate.
“`
func scrollToTop(animated: Bool = false) {
setContentOffset(CGPoint(x: contentOffset.x, y: -adjustedContentInset.top), animated: animated)
}
var bottomContentOffsetY: CGFloat {
max(contentSize.height – bounds.height + adjustedContentInset.bottom, -adjustedContentInset.top)
}
func scrollToBottom(animated: Bool = false) {
setContentOffset(CGPoint(x: contentOffset.x, y: bottomContentOffsetY), animated: animated)
}
func scrollToLeading(animated: Bool = false) {
setContentOffset(CGPoint(x: -adjustedContentInset.left, y: contentOffset.y), animated: animated)
}
var trailingContentOffsetX: CGFloat {
max(contentSize.width – bounds.width + adjustedContentInset.right, -adjustedContentInset.left)
}
func scrollToTrailing(animated: Bool = false) {
setContentOffset(CGPoint(x: trailingContentOffsetX, y: contentOffset.y), animated: animated)
}
func scrollViewToVisible(_ view: UIView, animated: Bool = false) {
scrollRectToVisible(convert(view.bounds, from: view), animated: true)
}
var isOnTop: Bool {
contentOffset.y = bottomContentOffsetY
}
}
“`
Let me look & verify. 🙂 Thanks for visiting blog, you can also check various articles related Swift,SwiftUI & DSA
May I ask why I didn’t receive the email after you replied to me?
There are some problems with the two functions of the above code, allow me to fix it
var isOnTop: Bool {
contentOffset.y = bottomContentOffsetY
}
The content displayed here is not consistent with what I submitted, please check the code here
https://pastebin.ubuntu.com/p/JsCBVgjTgG/
The content between the two angle brackets (greater than less than) is ignored as a comment.