Something that many people think should be included by default with a UIScrollView is a way to scroll to the bottom. Sadly, this is not the case. Because we are coders, we can easily add this feature.
First, create a new file called UIScrollView+Ext.swift in your project wherever it makes sense. Put this content in the file:
import UIKit
extension UIScrollView {
func scrollToBottom(animated: Bool = true) {
let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.height + self.contentInset.bottom)
self.setContentOffset(bottomOffset, animated: animated)
}
}
This code adds a scrollToBottom function to the UIScrollView class. The function calculates how much to vertically offset the content of the scroll view to make the bottom of the content visible. In this case, it is the content height, minus the height of the bounds (visible height), plus the bottom inset of the content. The scroll view is then scrolled to show the bottom of the content using the calculated offset.
An example usage of this function would be something like this:
@objc func scrollNowPressed(_ sender: Any?) {
scrollView.scrollToBottom(animated: false)
}
@objc func scrollSlowPressed(_ sender: Any?) {
scrollView.scrollToBottom(animated: true)
//scrollView.scrollToBottom() works too
}
I do hope this is helpful to someone, please let me know if you find this useful or if you have a better way of accomplishing a scroll-to-bottom effect for a UIScrollView.