scrollview paging in swift

UIScrollView can be set up to have paging with just a few lines of code.

Here's a basic example:

main.swift
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
scrollView.isPagingEnabled = true
view.addSubview(scrollView)

let contentView = UIView(frame: CGRect(x: 0, y: 0, width: scrollView.frame.width * 3, height: scrollView.frame.height))
scrollView.addSubview(contentView)

for i in 0..<3 {
    let pageView = UIView(frame: CGRect(x: CGFloat(i) * contentView.frame.width / 3, y: 0, width: contentView.frame.width / 3, height: contentView.frame.height))
    pageView.backgroundColor = UIColor(red: CGFloat(i)/3, green: CGFloat(i)/9, blue: CGFloat(i)/27, alpha: 1.0)
    contentView.addSubview(pageView)
}

scrollView.contentSize = contentView.frame.size
707 chars
15 lines

This sets up a UIScrollView with paging enabled and a content view that's three times as wide as the scroll view. It then adds three subviews to the content view, each one a third of the width of the content view and with a different background color (just to make it clear that they're separate pages).

If you run this code, you should be able to swipe left and right to page between the three subviews.

You can customize this to your specific needs by adjusting the number of pages and their contents.

related categories

gistlibby LogSnag