Create an Image Slideshow in Swift

Build a beautiful slideshow in your app

Ivano Di Gese
Oct 23 · 5 min read
Drawing of a slideshow in Swift
Drawing of a slideshow in Swift
Photo by the author.

Wrapping up multiple images in a single horizontal slideshow is a common task while developing iOS apps. Don’t think of it as the same old slider that you can see on webpages. Slideshows can be more common and useful than you might think.

Applications

Slideshows are useful for feed content like posts, contests, carousels (not real carousels but similar ones), and way more. I’ve used slideshows in a great variety of iOS apps, and they’ve always helped me when I needed to show multiple images inside small views.

Moreover, you can apply user interactions to them easily with gesture recognizers, providing the swipe behavior to show next and previous items inside the container and even tap or long-press gestures to apply events.

UIScrollView — It’s All You Need

First of all, let’s take a look at this UIView subclass. UIScrollView incorporates the behavior of encapsulating content that simply “scrolls” horizontally or vertically. UITableViews, UICollectionViews, and UI objects like these are simply subclasses of the UIScrollView class. They all scroll in a similar manner, actually.

The good thing about using UIScrollViews is that they provide delegation methods that let you benefit from having “hooks” and customize behaviors and code applications while the UIScrollView scrolls, stops scrolling, starts scrolling, or even decelerates.

Let’s take a look at the fundamental properties of the UIScrollView object:

  • contentSize: CGSize. Determine the content size of the UIScrollView. It’s used to specify how long the content inside the UIScrollView is.
  • contentOffset: CGPoint. It specifies the offset of the content using a CGPoint that has x and y coordinates. It’s used to offset the content (e.g. to “move” the content inside the UIScrollView).
  • contentInset: UIEdgeInsets. As any UIEdgeInset object, it’s used to set an inset space inside the UIScrollView. It’s like applying padding inside the UIScrollView.
  • isScrollEnabled: Bool. Determines if the UIScrollView should scroll. Useful when you have to lock or unlock the user interaction on the UIScrollView.
  • isPagingEnabled: Bool. If enabled, it makes the UIScrollView scrolling using pagination and avoiding a free and undetermined scrolling behavior. So if you swipe left for example, the UIScrollView slips to the next paged content.
  • bounces: Bool. If enabled, makes the UIScrollView bounces when its content come to the end or the beginning, providing the classic bouncing effect that you can see in many UI iOS controls.

Build Up Our UIScrollView as the Slideshow Container

You can obviously build a UIScrollView using the Storyboard or programmatically, and of course, you can even create a UIScrollView using a SwiftUI declarative approach.

Let’s try with the first approach using the Interface builder and the legacy Autolayout method:

Building a UIScrollView
Building a UIScrollView

In this example, we’ll go with:

  • A UILabel on top, with a top constraint to the Safe Area and a Center Horizontally constraint relative to the Safe Area as well.
  • A UIScrollView object placed just underneath the label. We apply a top constraint margin relative to the UILabel above and Trailing and Leading constraints relative to the Safe Area or the superview (which is the main UIView of our UIViewController).
Xcode warnings about ambiguous content size
Xcode warnings about ambiguous content size

You will notice that Xcode will prompt two warnings about ambiguous UIScrollView content size in terms of width and height. We didn’t set any content inside the scroll view and it’s impossible to determine “how much content” this object will actually display. These can be considered errors of the XIB (i.e. an Autolayout issue). Don’t worry about them too much because the XIB will show errors ignoring what you will code inside the controller. And obviously, we’ll incorporate the code that will provide specifications about the UIScrollView content size.

If you don’t have an XIB or prefer to code the layout, the basics remain the same. I often build my UI with Swift instead of the Interface builder depending on the project’s specs. Just be sure to place the object the correct way and apply its constraint using Swift classes or libraries like SnapKit.

Fill the Scrollview With Images and Apply the Swipe Behavior

Once you have the object in the UIViewController, you can fill it up with images. Images are usually provided by a web server as resources and are dynamic. That’s why I will assume you have a collection of images retrieved from wherever you want (storage, internet, cache, etc.) and just want to put them inside the slideshow.

Here are the steps:

  1. Loop through the array of UIImages.
  2. Create a UIImageView with the same width as the UIScrollView’s horizontal bounds and add the image inside it.
  3. Use the addSubview() method on the UIScrollView to add the UIImageView to the scrollview. In this step, you have to consider the horizontal offset because every UIImageView must be inserted after the previous one.
  4. When the loop has been completed, set the UIScrollView’s contentSize. This step is not automatic and must be coded. The UIScrollView object doesn’t get its contentSize based on what it’s inside. It must be set programmatically.

As you can see, you can build up a slideshow with a few lines of code just by setting the basic properties we discussed before. The only tricky part is the block where you instantiate the UIImageView and set offsets to make them stack horizontally. You can even try using a UIStackView to make it even more comfortable and easy to code, but it’s not much different.

Remember that if you need to make the slideshow slide horintally using a paged scrolling effect, you have to set the isPagingEnabled property. Otherwise, it will just be a scrollview that does not stick the scrolling animation to every page inside it.

And if you want to add a UIPageControl to display the current page indicator, you just have to use one of the most important UIScrollViewDelegate protocol methods:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let x = scrollView.contentOffset.x
let w = scrollView.bounds.size.width
pager.currentPage = Int(ceil(x/w))
}

Where the object named pager is your UIPageControl IBOutlet.

Conclusion

First of all, don’t copy/paste the code “as it is.” Try to understand the login and the output of this implementation. Some features and specifications should work depending on the goal you want to reach and the look and feel of the entire app.

One of the key factors is the UIImageView setup. Changing the frame, the contentMode of the images inside every UIImageView, and even applying effects on that object will make your app look way different. You can try adding a shadow layer on every image, captions, gradients, effects on taps, and so on. So take this as a mock slideshow and try to have more fun with it!

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store