Manually scrolling UIScrollView (iOS/Swift)
Recently while working with one of my libraries, I realized that I wanted to manually scroll UIScrollView
in any direction. (Viz. Top, Right, Bottom, Left). It took me quite time to find examples online. But I take this moment to compile them together.
Since Swift is a hot word in iOS kingdom, I will make a UIScrollView
extension with Swift which can be used to manually scroll the view in any direction.
In order to take advantage of Swift constructs, I have used enums
and encapsulated as much logic possible inside enum
since Swift enables us to include methods inside enum
.
Let's start with
enum
defining 4 directions
enum ScrollDirection {
case Top
case Right
case Bottom
case Left
}
Now let's include additional methods to this enum which will take UIScrollView
instance as a parameter and depending on the value of self
, it will return appropriate contentOffset
enum ScrollDirection {
case Top
case Right
case Bottom
case Left
func contentOffsetWith(scrollView: UIScrollView) -> CGPoint {
var contentOffset = CGPoint.zero
switch self {
case .Top:
contentOffset = CGPoint(x: 0, y: -scrollView.contentInset.top)
case .Right:
contentOffset = CGPoint(x: scrollView.contentSize.width - scrollView.bounds.size.width, y: 0)
case .Bottom:
contentOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
case .Left:
contentOffset = CGPoint(x: -scrollView.contentInset.left, y: 0)
}
return contentOffset
}
}
We are almost there. Now add an extension to
UIScrollView
which will take parameterdirection
of typeScrollDirection
and optional parameter which will indicate if we want scrolling action to be animated or not.
extension UIScrollView {
func scrollTo(direction: ScrollDirection, animated: Bool = true) {
self.setContentOffset(direction.contentOffsetWith(self), animated: animated)
}
}
So for example, if you want to manually scroll any UIScrollView
instance, you will just utilize the above code as follows,
let myScrollView = UIScrollView()
// With animation - Animation is enabled by default
myScrollView.scrollTo(.Top/.Right/.Bottom/.Left)
// Without animation
myScrollView.scrollTo(.Top/.Right/.Bottom/.Left, animated: false)
Hope this will help you in any of your side projects. The beauty of this approach is that we managed to move code which calculates content offset inside
enum
construct - MakingUIScrollView
extension easier to manage