UIScrollView Paging Swift 5

lyvennitha sasikumar
2 min readMay 5, 2021

UIScrollView is a boon to UI design in iOS. Many iOS developers still struggle to achieve a perfect scrollview for both horizontal and vertical scrolling. One of the most needed and hard to achieve is that swiping horizontally in a view changes the segment control from one segment to another without appling any gestures but purely used scrollview. In this blog i will explain how to achieve horizontal scrolling. Am done all the things with storyboard file.

Place a view controller in storyboard. And put a view and then place a scrollview inside that view. I will share the view hierarchy of my viewController and try the same.

Part — 1
Part — 2

Place segment control on top of the scroll view(Above the scroll view).

The Layout constraint of view is like human chain concept. Here i can add how layout is added for each view to achieve pagination.

View Layout

For changing segment on scroll is i use an extension for scrollview to scroll specific page of scrollview horizontally.

NOTE: You can use it for both horizontal and vertical scroll.

extension UIScrollView {
func scrollTo(horizontalPage: Int? = 0, verticalPage: Int? = 0, animated: Bool? = true) {
var frame: CGRect = self.frameframe.origin.x = frame.size.width * CGFloat(horizontalPage ?? 0)
frame.origin.y = frame.size.width * CGFloat(verticalPage ?? 0)
self.scrollRectToVisible(frame, animated: animated ?? true)
}
}

For segment value change action, we change frame as per the segment using that function in extention.

@IBAction func segmentAction(_ sender: UISegmentedControl){self.scrollView.scrollTo(horizontalPage: segment.selectedSegmentIndex, animated: true)}

To change segment on scrolling the scroll view

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {if scrollView.bounds.contains(view1.frame) {segment.selectedSegmentIndex = 0}if scrollView.bounds.contains(view2.frame) {segment.selectedSegmentIndex = 1}if scrollView.bounds.contains(view3.frame) {segment.selectedSegmentIndex = 2}}

Trying above results exact same in the results of above gif. For more queries please leave your valuable comments below.

Happy Coding! 🤎

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

lyvennitha sasikumar
lyvennitha sasikumar

Written by lyvennitha sasikumar

Passionate iOS developer chasing my dreams toward success

No responses yet

Write a response