Slideable TextViews in Swift with PageControl

Thomas
2 min readAug 4, 2021

If you are trying to achieve a similar design, as shown above, look no further. Let me show you how to build slideable TextViews in Swift using Storyboard with minimal coding. You can find an example repository at the end of the article.

Here are the steps you have to do on the Storyboard:

  1. Add a basic View to your ViewController, which will be the holder item.
  2. Inside the holder, add PageControl and a ScrollView.
  3. Now add your TextViews.
  4. Connect your ViewController with a Swift ViewController file.
  5. Create IBOutlets for your PageControl and your ScrollView.
Your ViewController (without Constraints) should look similar

Now comes the tricky part, adding constraints:

  1. Position the ViewHolder wherever you want to have it in your VC. In my case, I align it in the center of the screen and add trailing and leading constraints.
  2. Add a height constraint to your ViewHolder. That should be the height of your TextViews plus a margin for your ViewPager. For now, you may set it to a bigger size than needed to make editing easier.
  3. Position your ScrollView in the upper center with top, trailing, and leading constraints.
  4. Position your ViewPager at the bottom with bottom, trailing, and leading constraints and hook the top to the ScrollView.
  5. Add a height constraint to one of your TextViews. Only one is needed.
  6. Now you have to constraint every TextView to the SuperView and the neighboring TextView. Important: choose ScrollView instead of FrameLayout.
  7. Set the width to be equal to the ScrollView. Do this by holding CTRL and dragging your TextView onto the ScrollView. Choose Equal width.
  8. Change ViewHolder height to your calculated value.
Full Constraint List

After setting up your Interface, write this code snippet in your ViewController to connect PageControl with your ScrollView.

import UIKitclass ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var pageController: UIPageControl!
@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
super.viewDidLoad()
pageController.addTarget(self, action: #selector(self.pageChanged), for: .valueChanged)
scrollView.delegate = self
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageController.currentPage = Int(pageNumber)
}
@objc func pageChanged() {
let pageNumber = pageController.currentPage
var frame = scrollView.frame
frame.origin.x = frame.size.width * CGFloat(pageNumber)
frame.origin.y = 0
scrollView.scrollRectToVisible(frame, animated: true)
}
}

That’s it. Now you can display your TextViews with PageControl. You can check out my example GitHub repository here.

--

--